【发布时间】:2014-05-29 02:13:34
【问题描述】:
这是一个简单的 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) 在等待之前,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在await之后从SynchronizationContextTaskScheduler变成ThreadPoolTaskScheduler?
这基本上表现了TaskCreationOptions.HideScheduler for await 延续的行为,在我看来,这是出乎意料和不可取的。
这个问题是由我的另一个问题引发的:
AspNetSynchronizationContext and await continuations in ASP.NET.
【问题讨论】:
标签: c# .net task-parallel-library async-await