2016-12-08 54 views
0

我制作了一个程序,它需要一些文件,将它们重命名为一个随机数,然后将其保存到不同的文件夹中。我设法让代码做我想要的,但是它处理的文件有时很大,需要一段时间。这意味着用户有时会认为该程序已经崩溃。C#进度条带功能参数

我想添加一个进度条到程序,使其显而易见,它仍然工作,而不是崩溃。

我看过another question on how to add a progress bar,但是在我的情况下,功能需要摄入量,这取决于用户点击的按钮。

我不确定如何将它添加到我的代码中。理想情况下,我可以让backgroundWorker_DoWork采取额外的输入,所以它会是(object sender, DoWorkEventArgs e, string[] Files),但它似乎不可能。

任何帮助将不胜感激。

的相关功能下面的代码是:

private void blindSelected_Click(object sender, EventArgs e) 
    { 
     List<string> toBlind = new List<string>(); 
     // Find all checked items 
     foreach (object itemChecked in filesToBlind.CheckedItems) 
     { 
      toBlind.Add(itemChecked.ToString()); 
     } 
     string[] arrayToBlind = toBlind.ToArray(); 

     blind(arrayToBlind); 
    } 

    private void blindAll_Click(object sender, EventArgs e) 
    { 
     List<string> toBlind = new List<string>(); 
     // Find all items 
     foreach (object item in filesToBlind.Items) 
     { 
      toBlind.Add(item.ToString()); 
     } 
     string[] arrayToBlind = toBlind.ToArray(); 

     blind(arrayToBlind); 
    } 

    private void blind(string[] files) 
    { 
      // Generate an integer key and permute it 
      int[] key = Enumerable.Range(1, files.Length).ToArray(); 
      Random rnd = new Random(); 
      int[] permutedKey = key.OrderBy(x => rnd.Next()).ToArray(); 

      // Loop through all the files 
      for (int i = 0; i < files.Length; i++) 
      { 
       // Copy original file into blinding folder and rename 
       File.Copy(@"C:\test\" + files[i], @"C:\test\blind\" + permutedKey[i] + Path.GetExtension(@"C:\test\" + files[i])); 
      }    

      // Show completed result 
      MessageBox.Show("Operation complete!", "Done!", MessageBoxButtons.OK, MessageBoxIcon.Information); 
     } 

回答

1

考虑,我建议使用async/await你的代码,你可以谷歌它如何工作的细节。有了这些,你只能改变你的blind功能是这样的:

private async Task blind(string[] files) 
{ 
     // Generate an integer key and permute it 
     int[] key = Enumerable.Range(1, files.Length).ToArray(); 
     Random rnd = new Random(); 
     int[] permutedKey = key.OrderBy(x => rnd.Next()).ToArray(); 

     // Loop through all the files 
     for (int i = 0; i < files.Length; i++) 
     { 
      // Copy original file into blinding folder and rename 
      // Notice, this will wait for the Task to actually complete 
      await Task.Run(() => File.Copy(@"C:\test\" + files[i], @"C:\test\blind\" + permutedKey[i] + Path.GetExtension(@"C:\test\" + files[i]))); 
      someProgressBar.PerformStep(); // Or just set value by yourself 
     }    

     // Show completed result 
     MessageBox.Show("Operation complete!", "Done!", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 

这将保证您blind功能将异步运行。不要忘记添加someProgressBar

这有关于不能够抛出异常了,所以一定要处理得很好内部blind功能一些缺点 - 检查未能复制文件等