Advertisement
Guest User

Untitled

a guest
Apr 28th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. public void b1(object sender, EventArgs e)
  2. {
  3. for(int i = 0; i < 1000000; ++i)
  4. {
  5. ...
  6. }
  7. }
  8.  
  9. public void b2(object sender, EventArgs e)
  10. {
  11. ???
  12. }
  13.  
  14. CancellationTokenSource cts;
  15.  
  16. public async void b1(object sender, EventArgs e)
  17. {
  18. using (cts = new CancellationTokenSource())
  19. await Calculate(cts.Token);
  20. }
  21.  
  22. public void b2(object sender, EventArgs e)
  23. {
  24. cts.Cancel();
  25. }
  26.  
  27. Task Calculate(CancellationToken ct)
  28. {
  29. return Task.Run(() => CalculateImpl(ct));
  30. }
  31.  
  32. void CalculateImpl(CancellationToken ct)
  33. {
  34. for (int i = 0; i < 1000000; ++i)
  35. {
  36. if (ct.IsCancellationRequested)
  37. return;
  38. // ...
  39. }
  40. }
  41.  
  42. private BackgroundWorker bw;
  43.  
  44. public void b1(object sender, EventArgs e)
  45. {
  46. bw = new BackgroundWorker { WorkerSupportsCancellation = true };
  47. bw.DoWork += (obj, args) =>
  48. {
  49. BackgroundWorker lbw = (BackgroundWorker)obj;
  50. for (int i = 0; i < 1000000 && !lbw.CancellationPending; ++i)
  51. {
  52. ...
  53. }
  54. };
  55. bw.RunWorkerAsync();
  56. }
  57.  
  58. public void b2(object sender, EventArgs e)
  59. {
  60. if (bw != null && bw.IsBusy && !bw.CancellationPending)
  61. bw.CancelAsync();
  62. }
  63.  
  64. private volatile bool _isRunning;
  65.  
  66. private void buttonStart_Click (object sender, EventArgs e)
  67. {
  68. Task.Run(() => {
  69. _isRunning = true;
  70. for (int i = 0; i < 10000; i++) {
  71. Invoke((Action)(() => Text = i.ToString()));
  72. if (!_isRunning)
  73. break;
  74. }
  75. });
  76. }
  77.  
  78. private void buttonStop_Click (object sender, EventArgs e)
  79. {
  80. _isRunning = false;
  81. }
  82.  
  83. private volatile bool _stop_cycle;
  84.  
  85. public void b1(object sender, EventArgs e)
  86. {
  87. _stop_cycle = false;
  88. for(int i = 0; i < 1000000 && !_stop_cycle; ++i)
  89. {
  90. ...
  91. }
  92. }
  93.  
  94. public void b2(object sender, EventArgs e)
  95. {
  96. _stop_cycle = true;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement