Understanding the behavior of TaskScheduler.Current

前端 未结 1 717
野性不改
野性不改 2020-12-05 20:21

Here\'s a simple WinForms app:

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

nam         


        
相关标签:
1条回答
  • 2020-12-05 20:43

    If there is no actual task being executed, then TaskScheduler.Current is the same as TaskScheduler.Default. In other words, ThreadPoolTaskScheduler actually acts both as the thread pool task scheduler and the value meaning "no current task scheduler".

    The first part of the async delegate is scheduled explicitly using the SynchronizationContextTaskScheduler, and runs on the UI thread with both a task scheduler and synchronization context. The task scheduler forwards the delegate to the synchronization context.

    When the await captures its context, it captures the synchronization context (not the task scheduler), and uses that syncctx to resume. So, the method continuation is posted to that syncctx, which executes it on the UI thread.

    When the continuation runs on the UI thread, it behaves very similarly to an event handler; the delegate is executed directly, not wrapped in a task. If you check TaskScheduler.Current at the beginning of button1_Click, you'll find it is also ThreadPoolTaskScheduler.

    BTW, I recommend you treat this behavior (executing delegates directly, not wrapped in tasks) as an implementation detail.

    0 讨论(0)
提交回复
热议问题