public Form1() { InitializeComponent(); } // The following method runs asynchronously. The UI thread is not // blocked during the delay. You can move or resize the Form1 window // while Task.Delay is running. public async Task<string> WaitAsynchronouslyAsync() { await Task.Delay(10000); MessageBox.Show("fi"); return "Finished"; } // The following method runs synchronously, despite the use of async. // You cannot move or resize the Form1 window while Thread.Sleep // is running because the UI thread is blocked. public async Task<string> WaitSynchronously() { // Add a using directive for System.Threading. Thread.Sleep(10000); return "Finished"; } private async void button1_Click_1(object sender, EventArgs e) { string result = string.Empty; WaitAsynchronouslyAsync(); // Call the method that runs asynchronously. //result = await WaitAsynchronouslyAsync(); // Call the method that runs synchronously. // result = await WaitSynchronously (); // Display the result. textBox1.Text += result; MessageBox.Show("hi"); }上述代码得出至少两点:1. await WaitAsynchronouslyAsync() 执行时要等待这个调用完成,才会执下后面的代码,但在这个调用没有完成前,其thread是可以被其它代码占用的,表现就是UI仍可以接收其它消息2. WaitAsynchronouslyAsync()函数执行的线程与UI主线程是同一个,这也是为什么在这个函数中的messagebox可以显示,Thread.sleep可以阻止UI线程接收消息
时间: 2024-11-05 21:06:11