C# .Net并行(多核)编程 4 - Task的基本用法(复合的CancellationToken)
文章转自:http://ggicci.blog.163.com/blog/static/21036409620127204318184/
Title :
- Pro .NET 4 Parallel Programming in C# (Adam Freeman) Task的基本用法
- 复合的 Cancellation Token
Quote :
You can create a token that is composed from several CancellationTokens that will be cancelled if any of the underlying tokens is cancelled. [From “Pro .Net 4 Parallel Programming in C#”]
你可以把一些 CancellationToken 组合在一起形成一个复合的 CancellationToken,只要其中任何一个 CancellationToken 被取消,那么这个复合的就会被取消。
至于如何复合,只需调用 System.Threading.CancallationTokenSource.CreateLinkedTokenSource() 方法即可。
Code :
1: using System;2: using System.Threading;3: using System.Threading.Tasks;4:5: namespace Parallel_TaskProgramming6: {7: class Program8: {9: public static void Main(string[] args)10: {11: CancellationTokenSource tokenSource1 = new CancellationTokenSource();12: CancellationTokenSource tokenSource2 = new CancellationTokenSource();13: CancellationTokenSource tokenSource3 = new CancellationTokenSource();14: //用多个CancallationToken复合15: CancellationTokenSource compositeTokenSource =16: CancellationTokenSource.CreateLinkedTokenSource(17: tokenSource1.Token, tokenSource2.Token, tokenSource3.Token);18:19: Task task = new Task(() =>20: {21: int i = 0;22: while (true)23: {24: if (compositeTokenSource.Token.IsCancellationRequested)25: {26: throw new OperationCanceledException(compositeTokenSource.Token);27: }28: else29: {30: Console.WriteLine(i++);31: }32: }33: }, compositeTokenSource.Token);34:35: task.Start();36: Thread.Sleep(5);37: //只要其中一个子token被取消,任务就会被取消38: tokenSource1.Cancel();39:40: Console.WriteLine("Press enter to finish.");41: Console.ReadLine();42: }43: }44: }
Result :
1: 02: 13: 24: 35: 46: 57: 68: 79: 810: Press enter to finish.

浙公网安备 33010602011771号