Thursday, December 6, 2012

Cancelable tasks in .NET 4.0

There is new nice feature in .NET >= 4.0 - cancelling asynchronoums tasks.


Now you can do this:
 public class JobClass  
   {      
     private readonly CancellationTokenSource _cancellationSource;  
     public JobClass()  
     {  
       _cancellationSource = new CancellationTokenSource();        
     }              
     public void DoWork()  
     {  
         ...  
         Action action = () =>  
          {             
            foreach (var a in array)  
            {               
             /*do something*/  
             _cancellationSource.Token.ThrowIfCancellationRequested();  
            }  
          };  
        var task = new Task(action, _cancellationSource.Token);  
        task.Start();         
     }  
     public void Cancel()  
     {  
       _cancellationSource.Cancel();  
     }                       
   }  

As you can see, we created Task with cancellation Token. After this we can use cancellationSource to cancel this Task any time we want. It should be noted, that we use Token.ThrowIfCancellationRequested() method in async method body to throw exception if cancellation was requested.

No comments:

Post a Comment