Some overloads of Task.ContinueWith do not take a SynchronizationContext. What SynchronizationContext do they use to schedule the new task?
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
Actually, none of them take a
SynchronizationContext
, but some take aTaskScheduler
.None! By default, the continuation is scheduled by the current scheduler (
TaskScheduler.Current
), which, when not called from aTask
, isTaskScheduler.Default
. So the continuation is run on a thread from the thread pool.ThreadPool
threads don't have an associated synchronization context (unless you explicitly set one).By default,
ContinueWith
usesTaskScheduler.Current
for the continuation task, as can be seen in the Reference Source.This may be a source of confusion, because the current (ambient) task scheduler can be different from
TaskScheduler.Default
, and it can also be different from the scheduler of the task the continuation is attached to. That's why options likeTaskCreationOptions.HideScheduler
andTaskContinuationOptions.HideScheduler
were intriduced in .NET 4.5.It is recommended to always specify the task scheduler explicitly when calling
Task.Factory.StartNew
andTask.ContinueWith
. Most commonly, you'd specifyTaskScheduler.Default
(for the thread pool task scheduler) orTaskScheduler.FromCurrentSynchronizationContext()
.