PublicForm1 () {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 Asynctask<string>Waitasynchronouslyasync () {awaitTask.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 Asynctask<string>waitsynchronously () {//ADD a using directive for system.threading.Thread.Sleep (10000); return "finished"; } Private Async voidButton1_click_1 (Objectsender, EventArgs e) { stringresult =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"); }
The code above concludes at least two points:
1. Await Waitasynchronouslyasync () to wait for the call to complete before the subsequent code, but before the call is complete, its thread can be consumed by other code, the performance is that the UI can still receive other messages
2. The Waitasynchronouslyasync () function executes the same thread as the UI thread, which is why the MessageBox in this function can be displayed, Thread.Sleep can prevent the UI thread from receiving messages
Await, Anync