Why is TaskScheduler.Current the default TaskScheduler?

后端 未结 5 693
野趣味
野趣味 2020-11-30 20:25

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

5条回答
  •  北海茫月
    2020-11-30 20:48

    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.

提交回复
热议问题