C#-Task任务取消

 1 static void Main(string[] args)
 2         {
 3 
 4             var tasks = new List<Task<int>>();
 5             CancellationTokenSource source = new CancellationTokenSource();
 6             CancellationToken token = source.Token;
 7             // Define a delegate that prints and returns the system tick count
 8             Func<object, int> action = (object obj) =>
 9             {
10                 int i = (int)obj;
11 
12                 // Make each thread sleep a different time in order to return a different tick count
13                 Thread.Sleep(i * 100);
14 
15                 // The tasks that receive an argument between 2 and 5 throw exceptions
16                 if (2 <= i && i <= 5)
17                 {
18                     if (token.IsCancellationRequested)
19                         token.ThrowIfCancellationRequested();
20                     //source.Cancel();
21                     // if (token.IsCancellationRequested)
22                     //   
23                     // throw new AggregateException("SIMULATED EXCEPTION");
24                 }
25 
26                 int tickCount = Environment.TickCount;
27                 Console.WriteLine("Task={0}, i={1}, TickCount={2}, Thread={3}", Task.CurrentId, i, tickCount, Thread.CurrentThread.ManagedThreadId);
28 
29                 return tickCount;
30             };
31 
32             // Construct started tasks
33             for (int i = 0; i < 10; i++)
34             {
35                 int index = i;
36                 //tasks.Add(Task<int>.Factory.StartNew(action, index, source.Token));
37                 if (2 <= i && i <= 5)
38                 {
39                     tasks.Add(Task<int>.Factory.StartNew(action, index, source.Token));
40                 }
41                 else {
42                     tasks.Add(Task<int>.Factory.StartNew(action, index));
43                 }
44               
45             }
46 
47             try
48             {
49                 // Wait for all the tasks to finish.
50                 // 
51                // 
52                 Task.WaitAny(tasks.ToArray());
53                 source.Cancel();
54                 Thread.Sleep(5000);
55            
56                 foreach (var t in tasks)
57                 {
58                     Console.WriteLine("   Task {0}: {1}", t.Id, t.Status);
59                 }
60                 // We should never get to this point
61                 Console.WriteLine("WaitAll() has not thrown exceptions. THIS WAS NOT EXPECTED.");
62             }
63             catch (AggregateException e)
64             {
65                 foreach (Exception ea in e.InnerExceptions)
66                 {
67                     if (ea is TaskCanceledException)
68                         Console.WriteLine("Unable to compute mean: {0}",
69                                           ((TaskCanceledException)ea).Message);
70                     else
71                         Console.WriteLine("Exception: " + e.GetType().Name);
72                 }
73                     Console.WriteLine("\nThe following exceptions have been thrown by WaitAll(): (THIS WAS EXPECTED)");
74                 for (int j = 0; j < e.InnerExceptions.Count; j++)
75                 {
76                     Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());
77                 }
78             }
79             finally
80             {
81                 source.Dispose();
82             }
83         }

猜你喜欢

转载自www.cnblogs.com/alex-bian/p/12551038.html