Parallel Programming in C# Pro.Net Programming in C#, Adam Freeman
Parallel C# Task Parallel Library (TPL) TPL tasks vs. Threads Benefits & Pitfalls of Parallel Programming Overhead Coordinating fata Scaling Applications
Task Programming Creating and starting tasks Task.Factory.StartNew() Task.Start() Setting task state System.Action Passing parameters to tasks Getting a result Task.Result
Task Programming Task creation options PreferFairness LongRunning AttachedToParent Identifying tasks Task.CurrentId
Cancelling tasks Simpler, more consistent and reduced risk task creation Steps: Create a new instance of CancellationTokenSource Call CancellationTokenSource.Token property to get a Cancellationtoken Create a new task with this token Call Start() method of the task to start this task Call CancellationTokenSource.Cancel() method to cancel the task
Cancelling tasks Who is responsible of cancelling a task? Cancellation procedure in a task Polling Using a delegate Cancelling with a wait handle Cancelling several tasks Composite cancellation tokens Determine task is cancelled
Waiting time to pass Sleeping Using cancellation token wait handle Using classic Thread.Sleep() Using Thread.SpinWait()
Waiting for tasks What if there is no Task.Result? Waiting for single task: Wait(), Wait(CancellationToken), Wait(Int32), Wait(TimeSpan), Wait(Int32, CancellationToken) Wait for several tasks: WaitAll(), WaitAny()
Handling exceptions Basic exceptions: AggregateException Iterative handler: AggregateException.Handle() Reading task properties: IsCompleted IsFaulted IsCancelled Exception
Getting status of a task Created WaitingForActivation || WaitingToRun Running WaitingForChildrenToComplete RanToCompletion Canceled Faulted
Executing tasks lazily Execute task when needed. Anonymous functions Lazy
Common problems Task dependency deadlock Local variable evaluation Excessive spinning