2018年9月9日 星期日

【C#】IProgress

IProgress 是類似輕量化版的 BackgroundWorker

它沒有 IsBusy, WorkComplete 事件等,要自己做,但我覺得比較直觀,貌似對 async 的支援也好點。
  1. public partial class Form1 : Form
  2. {
  3. IProgress<int> _progress;
  4. public Form1()
  5. {
  6. InitializeComponent();
  7.  
  8. _progress = new Progress<int>(UpdateProgressBar);
  9. }
  10.  
  11. private void UpdateProgressBar(int val)
  12. {
  13. pbProgress.Value = val;
  14.  
  15. if (val == 100)
  16. {
  17. MessageBox.Show("Finished");
  18. pbProgress.Value = 0;
  19. }
  20. }
  21.  
  22. private async void btnStart_Click(object sender, EventArgs e)
  23. {
  24. if (pbProgress.Value == 0)
  25. {
  26. await Task.Run(async () =>
  27. {
  28. for (int i = 0; i < 100; i++)
  29. {
  30. _progress.Report(i + 1);
  31. await Task.Delay(100 - i);
  32. }
  33. });
  34. }
  35. }
  36. }

ref: GitHub 範例(Form2是 backgroundworker,可以在 program 切換)

沒有留言:

張貼留言