執行關於這段代碼:爲什麼異步回調在WPF UI線程
static async Task<string> testc()
{
Console.WriteLine("helo async " + Thread.CurrentThread.ManagedThreadId);
await Task.Run(() => {
Thread.Sleep(1000);
Console.WriteLine("task " + Thread.CurrentThread.ManagedThreadId);
});
Console.WriteLine("callback "+Thread.CurrentThread.ManagedThreadId);
return "bob";
}
static void Main(string[] args)
{
Console.WriteLine("helo sync " + Thread.CurrentThread.ManagedThreadId);
testc();
Console.WriteLine("over" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.ReadLine();
}
我得到以下輸出:
helo sync 10
helo async 10
over10
task 11
callback **11**
這是確定:的await後的代碼中執行與任務本身相同的線程。
現在,如果我做一個WPF應用程序:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Console.WriteLine("helo sync " + Thread.CurrentThread.ManagedThreadId);
testc();
Console.WriteLine("over" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.ReadLine();
}
它會生成以下的輸出:
helo sync 8
helo async 8
over8
task 9
callback **8**
這裏我們可以看到代碼後,在UI線程伺機執行。那麼,這是偉大的,因爲它可以操縱可觀察的集合等......但我想知道「爲什麼?」 「我怎麼能這樣做?」這與某些TaskScheduler行爲有關嗎?這是在.NET Framework中硬編碼的嗎?
Thx對於您可能提交的任何想法。
+1需要更多的重視您的BTW。 – Phill 2013-04-25 08:07:22