. NET 4.5 includes a cancellation schema that allows for a standard way to cancel long-running tasks. Each blocking call should support this mechanism. But for now, not all blocking calls have implemented this new technology. The technology that has implemented this mechanism has the task (http://www.cnblogs.com/afei-24/p/6907840.html), the Concurrent collection class (http://www.cnblogs.com/afei-24/p/6836976. HTML), parallel LINQ (Http://www.cnblogs.com/afei-24/p/6860753.html), and several synchronization mechanisms.
canceling a schema is based on collaborative behavior, and it is not mandatory. A long-running task checks whether it is canceled and returns control.
the method that supports cancellation accepts a cancellationtoken parameter. This class defines the IsCancellationRequested property, where a long-running operation can check if it should terminate. Use the Register () method to register a delegate that will be called when this System.Threading.CancellationToken is canceled. It is called when the Cancel () method is called.
cancellation of the 1.parallel.for () method
The parallel class provides an overloaded version of the for () method, and in overloaded versions, parameters of the ParallelOptions type can be passed. With the paralleloptions type, you can pass a cancellationtoken parameter. The CancellationToken parameter is generated by creating a cancellationtokensource. Because CancellationTokenSource implements the Icancelableoperation interface, it can be registered with CancellationToken and allows the operation to be canceled using Cancle (), Cancleafter (), and so on.
Example:
Static voidcancelparallelfor () {varAT1 =NewCancellationTokenSource (); Cts. Token.register (()= Console.WriteLine ("token canceled!")); Cts. Cancelafter ( +); Try{Parallelloopresult PLR=Parallel.For (0, -,Newparalleloptions {CancellationToken =CTS. Token}, X={Console.WriteLine ("Loop {0} started", x); Thread.Sleep ( +); Console.WriteLine ("Loop {0} fininshed!", x); }); } Catch(OperationCanceledException ex) {Console.WriteLine (ex). Message); } }
Output:
In the implementation code for the For loop, the parallel class validates the results of the cancellationtoken and cancels the operation. Once the operation is canceled, the for () method throws an exception of type operationcanceledexception.
As can be seen from the output, when the operation is canceled, the initiated action allows completion because the cancel operation is always done cooperatively to avoid leaking resources in the middle of canceling the iteration operation.
2. Cancellation of tasks
Cancellation of the task resembles the cancellation of the Parallel.For () method. First, create a cancellationtokensource. If you only need a cancellation token, you can access the Task.Factory.CancellationToken to use the default cancellation token. The task accepts the cancellation token through the TaskFactory object. In the constructor, assign the cancellation token to TaskFactory. This cancellation token and task is used to check the IsCancellationRequested property of the CancellationToken to determine if cancellation was requested.
Example:
Static voidCanceltask () {varCTS =NewCancellationTokenSource (); Cts. Token.register (()= Console.WriteLine ("Task cancelled!")); Cts. Cancelafter ( -); Try{Task T= Task.run (() ={CancellationToken token=CTS. Token; Console.WriteLine ("Task stared!"); for(inti =0; I < -; i++) {Thread.Sleep ( -); if(CTS. iscancellationrequested) {Console.WriteLine ("cancelled!"); Token. Throwifcancellationrequested ();//Throw Exception Break; } Console.WriteLine ("In loop!"); }}, CTS. Token); T.wait (); } Catch(AggregateException ex) {Console.WriteLine ("Exception:{0},{1}", ex. GetType (). Name,ex. Message); foreach(varInnerexinchEx. InnerExceptions) {Console.WriteLine ("Exception:{0},{1}", ex. Innerexception.gettype (). Name, ex. Innerexception.message); } } }
Output:
Multi-Thread Cancellation schema