这是一个简单的WinForms应用程序:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
var ts = TaskScheduler.FromCurrentSynchronizationContext();
await Task.Factory.StartNew(async () =>
{
Debug.WriteLine(new
{
where = "1) before await",
currentTs = TaskScheduler.Current,
thread = Thread.CurrentThread.ManagedThreadId,
context = SynchronizationContext.Current
});
await Task.Yield(); // or await Task.Delay(1)
Debug.WriteLine(new
{
where = "2) after await",
currentTs = TaskScheduler.Current,
thread = Thread.CurrentThread.ManagedThreadId,
context = SynchronizationContext.Current
});
}, CancellationToken.None, TaskCreationOptions.None, scheduler: ts).Unwrap();
}
}
}
调试输出(单击按钮时):
{where = 1}在await之前,currentTs = System.Threading.Tasks.SynchronizationContextTaskScheduler,thread = 9,context = System.Windows.Forms.WindowsFormsSynchronizationContext} {where = 2}等待之后,currentTs = System.Threading.Tasks.ThreadPoolTaskScheduler,thread = 9,context = System.Windows.Forms.WindowsFormsSynchronizationContext}
问题是: 为什么是 TaskScheduler.Current
改变 SynchronizationContextTaskScheduler
至 ThreadPoolTaskScheduler
后 await
这里?
这基本上表现出这种行为 TaskCreationOptions.HideScheduler
对于 await
在我看来,延续,这是意想不到的和不可取的。
这个问题是由我的另一个问题引发的: