- The
CancellationTokenSource.CreateLinkedTokenSourcecan linked multipleCancellationTokenSourceto stop task whatever linked token be fired.
Task.WaitAll(t1, t2)waiting for the longest task. In the sample will be waiting thet1task completedTask.WaitAny(t1, t2)waiting for the first completed task. In the sample will be waiting thet2task completedTask.WaitAny(new[] { t1, t2 }, 4000)only waiting for 4 seconds. In the sample will be waiting thet2task completed
Interlocked.Addto add new value to origin one.Interlocked.Incrementto increment one to origin value.Interlocked.Decrementto decrement one to origin value.Interlocked.MemoryBarriershorthand forThread.MemoryBarrier().- Synchronizes memory access as follows.
Interlocked.Exchangesets a variable to a specified value as an atomic operation.SpinLockobject for atomic operation that until you are able to execute.SpinLock(true)enable thread owner tracking.
- Mutex object
- Can shared between server different processes.
- Reader-Writer locks
- Support lock recursion in ctor paramater but not recommended.
ConcurrentDictionaryasking to count that's an expensive operation.ConcurrentQueueConcurrentStackprovides theTryPopRangeto pop items at once.ConcurrentBagprovides no ordering guarantees.BlockingCollectionis a wrapper around one of theIProducerConsumerCollectionclasses.- Provides blocking and bounding capabilites.
-
Contiuation
ContinueWithapi provides to continue next task.- Continuations can be conditional.
- TaskContinuationOptions.NotOnFaulted.
- Beware of waiting on continuations that might not occur by faulted. That will be waiting forever.
- Continuations can be conditional.
Task.Factory.ContinueWhenAllprovides api to waiting for all tasks.- One-to-many continuations.
Task.Factory.ContinueWhenAnyprovides api to waiting any first completed task.- One-to-any continuations.
-
Child task
TaskCreationOptions.AttachedToParentfor attach to parent.TaskContinuationOptions.OnlyOnRanToCompletioncontinue when task ran to completion.TaskContinuationOptions.OnlyOnFaultedcontinue when task ran to failted.
-
Synchronization Primitives
-
All do same thing.
- They have a counter.
- Let you execute N threads at a time.
- Other threads are unblocked until state changes.
-
Barrier- Blocks all threads until N are waiting , then lets those N through via
SignalAndWait().
- Blocks all threads until N are waiting , then lets those N through via
-
CountdownEvent- Signaling and waiting separate; waits until signal level reaches 0, then unblocks.
-
ManualResetEventSlim- Like
CountdownEventwith a count of 1. Set()to release all block threads. AfterSet()signaled, threads that callWaitOne()do not block.Resetstarting block threads.
- Like
-
AutoResetEvent- Resets after waiting.
-
SemaphoreSlim- Counter
CurrentCountdecreased byWait()and increased byRelease(N). - Can have a maximum.
- Counter
-
- Parallel.For/Foreach are blocking calls
- Wait until threads completed or an exception occurred.
- Can check the state of the loop as it is executing in
ParallelLoopState. - Can check result of execution in
ParallelLoopResult. ParallelLoopOptionlet us customize execution with:- Max degree of parallelism.
- Cancellation token.
Parallel.Invoke- Run several provided functions concurrently.
- Is equivalent to:
- Creating a task for each lambda.
- Doing a
Task.WaitAll()on all the tasks.
Parallel.For- Uses an index [start; finish].
- Cannot provide a step.
- Create an
IEnumerable<int>and useParallel.ForEach
- Create an
- Partitions data into different tasks.
- Execute provided delegate with counter value argument.
- Might be inefficient.
Parallel.ForEach- Like
Parallel.Forbut takes anIEnumerable<T>instead. - If enumerator using
yeild returnthat must watch out cause you're never going to find out how long the total number of elements is.
- Like
- Thread local storage
- Writing to a shared variable from many tasks is inefficient.
- Interlocked every time.
- Can store partially evaluated results for each task.
- Can specify a function to integrate partial results into final result.
- Writing to a shared variable from many tasks is inefficient.
- Partitioning
- Data is split into chunks by a
Partitioner. - Can create your own.
- Goal is improve performance.
- Void costly delegate creation calls.
- Data is split into chunks by a
- Turn Linq query parallel by
- Calling
AsParallel()on an IEnumerable. - Use a
ParallelEnumerable
- Calling
- Use
WithCancellation()to provide a cancellation token. - Catch
AggregateExceptionOperationCanceledExceptionif expecting to cancel.
WithMergeOptions(ParallelMergeOptions.xxx)determine how soon produced result can be consumed.- Parallel version of
Aggregateprovides a syntax for custom per-task aggregation options.
- What does await do?
- Registers continuation with the async operation.
- In other words, "code that follows me is a continuation, like
ContinueWith()"
- In other words, "code that follows me is a continuation, like
- Gives up the current thread.
- It's over. We no longer do anything on the current thread.
- The call happens on a thread from TPL thread pool.
- If
SynchroizationContext.Current!= null, ensures the continuation is also posted there(e.g., on the UI thread)- If null, continuation scheduled using current task scheduler.
- This behavior can be customized right on the call.
- Coerces the result of the asynchronous operation.
- Registers continuation with the async operation.
Task.Run- Equivalent to
- Task.Factory.StartNew(something, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
- Provides 8 overloads to support combinations of
- Task vs Task
- Cancelable vs Non-Cancelable.
- Synchronous vs asynchronous delegate.
- Equivalent to
awaitcan be used a the language equivalent ofUnwrap()- Task Utility Combinators
- Kind of like
Task.WaitAll/WaitAny, but block the current thread. - Crate brand new tasks (useful for async/await)
Task.WhenAny- Creates a task that will complete when any of the supplied tasks has completed.
- await Task.WhenAny(downloadFromHttp, downloadFromFtp);
Task.WhenAll()- Creates a task that will complete when all of the supplied task have completed.
- await Task.WhneAll(measureTemperature, measurePressure);
- Kind of like
- Asynchronous programming is enableed with the
asyncandawaitkeywords. - Methods that
awaitmust be decorated withasync. - When you await, you abandon current thread, fire up a new one and then do a context-preserving continuation of the code that's left.
- You can call async method synchronously.
- .net 4.5 gives us awaitable
Task.Delayand combinators.