只有发出请求的对象,才能发出取消请求,而每个侦听器负责侦听是否有请求,并及时适当地响应请求。

  用于实现协作取消模型的常规模式是:

 

  1. CancellationTokenSource 对象,此对象管理取消通知并将其发送给单个取消标记。
  2. CancellationTokenSource.Token 属性返回的标记传递给每个侦听取消的任务或线程。
  3. 为每个任务或线程提供响应取消的机制。
  4. CancellationTokenSource.Cancel 方法以提供取消通知。

值变为 true 后,侦听器可以适当方式终止操作。

 1 using System;
 2 using System.Threading;
 3 
 4 public class Example
 5 {
 6    public static void Main()
 7    {
 8       // Create the token source.
 9       CancellationTokenSource cts = new CancellationTokenSource();
10 
11       // Pass the token to the cancelable operation.
12       ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts.Token);
13       Thread.Sleep(2500);
14 
15       // Request cancellation.
16       cts.Cancel();
17       Console.WriteLine("Cancellation set in token source...");
18       Thread.Sleep(2500);
19       // Cancellation should have happened, so call Dispose.
20       cts.Dispose();
21    }
22 
23    // Thread 2: The listener
24    static void DoSomeWork(object obj)
25    {
26       CancellationToken token = (CancellationToken)obj;
27 
28       for (int i = 0; i < 100000; i++) {
29          if (token.IsCancellationRequested)
30          {
31             Console.WriteLine("In iteration {0}, cancellation has been requested...",
32                               i + 1);
33             // Perform cleanup if necessary.
34             //...
35             // Terminate the operation.
36             break;
37          }
38          // Simulate some work.
39          Thread.SpinWait(500000);
40       }
41    }
42 }
43 // The example displays output like the following:
44 //       Cancellation set in token source...
45 //       In iteration 1430, cancellation has been requested...
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
猜你喜欢
  • 2022-02-21
  • 2022-12-23
  • 2021-12-01
  • 2022-12-23
  • 2022-02-01
  • 2021-07-13
  • 2022-12-23
相关资源
相似解决方案