Why is TaskScheduler.Current the default TaskScheduler?

后端 未结 5 696
野趣味
野趣味 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:53

    I think the current behavior makes sense. If I create my own task scheduler, and start some task that starts other tasks, I probably want all the tasks to use the scheduler I created.

    I agree that it's odd that sometimes starting a task from the UI thread uses the default scheduler and sometimes not. But I don't know how would I make this better if I was designing it.

    Regarding your specific problems:

    • I think the easiest way to start a new task on a specified scheduler is new Task(lambda).Start(scheduler). This has the disadvantage that you have to specify type argument if the task returns something. TaskFactory.Create can infer the type for you.
    • You can use Dispatcher.Invoke() instead of using TaskScheduler.FromCurrentSynchronizationContext().

提交回复
热议问题