2016-12-08 100 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功能一些缺點 - 檢查未能複製文件等