The Task Parallel Library is great and I\'ve used it a lot in the past months. However, there\'s something really bothering me: the fact that TaskScheduler.Current is the de
It's not obvious at all, Default is not the default! And the documentation is seriously lacking.
Default
is the default, but it's not always the Current
.
As others have already answered, if you want a task to run on the thread pool, you need to explicitly set the Current
scheduler by passing the Default
scheduler into either the TaskFactory
or the StartNew
method.
Since your question involved a library though, I think the answer is that you should not do anything that will change the Current
scheduler that's seen by code outside your library. That means that you should not use TaskScheduler.FromCurrentSynchronizationContext()
when you raise the SomeOperationCompleted
event. Instead, do something like this:
public void DoSomeOperationAsync() {
var context = SynchronizationContext.Current;
Task.Factory
.StartNew(() => Thread.Sleep(1000) /* simulate a long operation */)
.ContinueWith(t => {
context.Post(_ => OnSomeOperationCompleted(), null);
});
}
I don't even think you need to explicitly start your task on the Default
scheduler - let the caller determine the Current
scheduler if they want to.