Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void b1(object sender, EventArgs e)
- {
- for(int i = 0; i < 1000000; ++i)
- {
- ...
- }
- }
- public void b2(object sender, EventArgs e)
- {
- ???
- }
- CancellationTokenSource cts;
- public async void b1(object sender, EventArgs e)
- {
- using (cts = new CancellationTokenSource())
- await Calculate(cts.Token);
- }
- public void b2(object sender, EventArgs e)
- {
- cts.Cancel();
- }
- Task Calculate(CancellationToken ct)
- {
- return Task.Run(() => CalculateImpl(ct));
- }
- void CalculateImpl(CancellationToken ct)
- {
- for (int i = 0; i < 1000000; ++i)
- {
- if (ct.IsCancellationRequested)
- return;
- // ...
- }
- }
- private BackgroundWorker bw;
- public void b1(object sender, EventArgs e)
- {
- bw = new BackgroundWorker { WorkerSupportsCancellation = true };
- bw.DoWork += (obj, args) =>
- {
- BackgroundWorker lbw = (BackgroundWorker)obj;
- for (int i = 0; i < 1000000 && !lbw.CancellationPending; ++i)
- {
- ...
- }
- };
- bw.RunWorkerAsync();
- }
- public void b2(object sender, EventArgs e)
- {
- if (bw != null && bw.IsBusy && !bw.CancellationPending)
- bw.CancelAsync();
- }
- private volatile bool _isRunning;
- private void buttonStart_Click (object sender, EventArgs e)
- {
- Task.Run(() => {
- _isRunning = true;
- for (int i = 0; i < 10000; i++) {
- Invoke((Action)(() => Text = i.ToString()));
- if (!_isRunning)
- break;
- }
- });
- }
- private void buttonStop_Click (object sender, EventArgs e)
- {
- _isRunning = false;
- }
- private volatile bool _stop_cycle;
- public void b1(object sender, EventArgs e)
- {
- _stop_cycle = false;
- for(int i = 0; i < 1000000 && !_stop_cycle; ++i)
- {
- ...
- }
- }
- public void b2(object sender, EventArgs e)
- {
- _stop_cycle = true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement