Multi-Threaded #45

1_tasks

We saw the Task.Run (.NET 4.5) and the Task.Factory.StartNew which are a short and simple way to create and start a task (the difference between them is that Task.Factory.StartNew supports LongRunning operations [non threadpool threads]).we talked about Task.ContinueWith. the Continue-with creates a continuation task and executes it after the first task is completed. The continuation task is executed or not based on a set of specified conditions provided by the  TaskContinuationOptions enum, for example: continue to the next task only if the previous task completed successfully, etc. tasks have a built-in mechanism for cancellation called cancellation token (part of the CancellationTokenSource). the cancellation token is a struct which enables cooperative cancellation between tasks. When the owning object calls CancellationTokenSource.Cancel, the IsCancellationRequested property is set to true. this means that in the tasks that we write we should check the cancellation token state.  if the state is cancelled- we could decide how to proceed, for example: quit the method, ignore, throw OperationCancelledException (using built-in ThrowIfCancellationRequested method) , etc. we saw that whenever an exception occur inside a task- it is nested inside an AggregationException. since tasks are running on a background threads- the exception thrown inside a tasks does not “crash” the program. however, if we try to Wait for a faulted task or retrieve the Result from a faulted task: AggregationException will be thrown (which could crash our program, if not handled). so the best approach will be to try-catch the Wait or to check whether the task is faulted or not, then if it is faulted- use the Task.Exception.Handle method

More topics covered:

  • Task.ContinueWith should keep the same return value
  • Task.ContinueWith creates a parent-child tasks
  • In the Task.ContinueWithThe child task will be executed even if the parent task throws an exception
  • ThrowIfCancellationRequested throws an exception only if the token was cancelled
  • Dependency injection

Links:

 

Leave a comment