fork download
  1. var worker = new BackgroundWorker()
  2. {
  3. WorkerReportsProgress = true,
  4. WorkerSupportsCancellation = true,
  5. };
  6.  
  7. var form = new Form();
  8. var statusStrip = new StatusStrip();
  9. var toolStripProgressBar = new ToolStripProgressBar()
  10. {
  11. Minimum = 0,
  12. Maximum = 10,
  13. };
  14. statusStrip.Items.Add(toolStripProgressBar);
  15.  
  16. var cancelButton = new Button()
  17. {
  18. Location = new Point(110, 0),
  19. Size = new Size(100, 50),
  20. Text = "Cancel",
  21. Enabled = false,
  22. };
  23. cancelButton.Click += (sender, e) =>
  24. {
  25. if (!worker.IsBusy) return;
  26. cancelButton.Enabled = false;
  27. worker.CancelAsync();
  28. };
  29.  
  30.  
  31. var button = new Button()
  32. {
  33. Size = new Size(100, 50),
  34. Text = "Start",
  35. };
  36. button.Click += (sender, e) =>
  37. {
  38. if (worker.IsBusy) return;
  39. button.Enabled = false;
  40. cancelButton.Enabled = true;
  41. worker.RunWorkerAsync(null);
  42. };
  43.  
  44.  
  45.  
  46. form.Controls.Add(statusStrip);
  47. form.Controls.Add(button);
  48. form.Controls.Add(cancelButton);
  49.  
  50. form.Load += (x, y) =>
  51. {
  52. worker.DoWork += (sender, e) =>
  53. {
  54. // e.Result;
  55. var args = e.Argument;
  56.  
  57. for (int i = 0; i < 10; i++)
  58. {
  59. if (worker.CancellationPending)
  60. {
  61. e.Cancel = true;
  62. return;
  63. }
  64.  
  65. worker.ReportProgress(i, null);
  66. Thread.Sleep(1000);
  67.  
  68. if (i == 5)
  69. {
  70. throw new ApplicationException();
  71. }
  72. }
  73. };
  74. worker.RunWorkerCompleted += (sender, e) =>
  75. {
  76. toolStripProgressBar.Value = toolStripProgressBar.Minimum;
  77. button.Enabled = true;
  78. cancelButton.Enabled = false;
  79.  
  80. if (null != e.Error)
  81. {
  82. System.Windows.Forms.MessageBox.Show(form, e.Error.ToString(), e.Error.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
  83. return;
  84. }
  85. if (e.Cancelled)
  86. {
  87. MessageBox.Show(form, "処理はキャンセルされました。", "処理のキャンセル");
  88. return;
  89. }
  90. // e.Result
  91. // e.UserState
  92. MessageBox.Show(form, "処理が終了しました。", "終了");
  93. };
  94.  
  95. worker.ProgressChanged += (sender, e) =>
  96. {
  97. // var userState = e.UserState;
  98. toolStripProgressBar.Value = e.ProgressPercentage;
  99. };
  100. };
  101.  
  102. Application.Run(form);
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty