[C #] performing asynchronous operations in the GUI,
Perform asynchronous operations in the GUI
Collation
Directory
1. Perform asynchronous operations in the GUI Program
The following is an example of the form to demonstrate the following operations-click the button: ① change the TAG content to "Doing" and disable the button (indicating that the tag is being executed ); ② The thread hangs for 3 seconds (simulating time-consuming operations); ③ enable the button to change the label content to "Complete" (indicating that the execution is Complete );
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 8 private void btnDo_Click(object sender, EventArgs e) 9 {10 btnDo.Enabled = false;11 lblText.Text = @"Doing";12 13 Thread.Sleep(3000);14 15 btnDo.Enabled = true;16 lblText.Text = @"Complete";17 }18 }
However, the execution result is:
Figure 1-1
The problem found: It seems that it has not changed to "Doing", and the window is stuck when you drag it. After three seconds, the text suddenly changes to the position where you want to drag it, and the text changes to "Complete "?
[Analysis] GUI program design requires that all the display changes must be completed in the main GUI thread, such as click events and move forms. Messages are implemented through messages in a Windows program. messages are placed in the message queue managed by the message pump. When you Click the button, the Click message of the button is placed in the message queue. The message pump removes the message from the queue and starts to process the code of the click event, that is, the code of the btnDo_Click event. The btnDo_Click event puts messages that trigger behavior into the queue. However, messages cannot be executed until the btnDo_Click time processing program exits (the thread suspends 3 seconds ago. Then all the actions happen, but the speed is too fast to be identified by the naked eye.
Figure 1-2 Click Event
Figure 1-3 specific execution process of click events
[Analysis] If the btnDo_Click event handler can first push the first two messages into the queue, then remove himself from the processor, and then press himself into the queue four seconds later. In this way, the response can be maintained and all messages can be processed within the time when the thread is suspended.
Now we add the async/await feature.
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 8 private async void btnDo_Click(object sender, EventArgs e) 9 {10 btnDo.Enabled = false;11 lblText.Text = @"Doing";12 13 await Task.Delay(3000);14 15 btnDo.Enabled = true;16 lblText.Text = @"Complete";17 }18 }
Figure 1-4
Now, it's what I want to see.
Http://www.cnblogs.com/liqingwen/p/5877042.html.