Winform
private async Task DoAsync() { Console.WriteLine("DoAsync_Befor:" + Thread.CurrentThread.ManagedThreadId); for (int i = 0; i < 10; i++) { await Task.Run(() => { //Thread.Sleep(100); Console.WriteLine("in:" + Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine("DoAsync_After:" + Thread.CurrentThread.ManagedThreadId); } } private void button2_Click(object sender, EventArgs e) { Console.WriteLine("button2_Click_befor:" + Thread.CurrentThread.ManagedThreadId); DoAsync(); Console.WriteLine("button2_Click_after:" + Thread.CurrentThread.ManagedThreadId); //Console.Read(); }
Console
static void Main(string[] args) { Console.WriteLine("Main_befor:" + Thread.CurrentThread.ManagedThreadId); DoAsync(); Console.WriteLine("Main_after:" + Thread.CurrentThread.ManagedThreadId); Console.Read(); } private static async Task DoAsync() { Console.WriteLine("DoAsync_Befor:" + Thread.CurrentThread.ManagedThreadId); for (int i = 0; i < 10; i++) { await Task.Run(() => { Thread.Sleep(100); Console.WriteLine("in:" + Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine("DoAsync_After:" + Thread.CurrentThread.ManagedThreadId); } }
Winform 的DoAsync_After 始终是1,即 UI线程
而Console输出有多个情况,即Task.Run(...)中使用的线程,
所以在Winform中async与await是做特定处理的