Task (TPL) Winform (WPF) to achieve a simple asynchronous

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

  Most of the time, we must realize the Winform asynchronous operations, you can use the traditional method, but personal feeling code is not well understood, and the use is really a bit uncomfortable. You can also use the Task to achieve, Task (object.Net4.0 newly added) is actually to the thread pool threads of a package, which has more functions, better operation, other do not say, today only the asynchronous operation, cite a simple example.:

  The first chart: click the Go button, the digital automatic increase, relatively simple.

  

 Directly on the code:

 1  public partial class Form1 : Form
 2     {
 3         private CancellationTokenSource cts = null;//Mainly for the interrupted thread
 4         private TaskScheduler taskScheduler;
 5 
 6         public Form1()
 7         {
 8             InitializeComponent();
 9 
10              //Gets the current thread context
11             taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
12         }
13 
14         /*The traditional method*/
15         private void UpdateText(string text)
16         {
17             if (this.InvokeRequired)
18                 btnTask.Invoke(new Action<string>(UpdateText), text);
19             else
20                 btnTask.Text = text;
21         }
22 
23         private void GoByThread()
24         {
25             Thread thread = new Thread(() =>
26             {
27                 for (int i = 0; ; i++)
28                 {
29                     Thread.Sleep(200);
30                     UpdateText(i.ToString());
31                 }
32             });
33 
               thread.IsBackground=true;

34 thread.Start(); 35 } 36 37 /*Task*/ 38 private void GoByTask() 39 { 40 if (cts == null) 41 { 42 cts = new CancellationTokenSource(); 43 44 Task.Factory.StartNew(() => 45 { 46 for (int i = 0; ; i++) 47 { 48 Thread.Sleep(200); 49 50 //The following is the key code, An Task 51 Task.Factory.StartNew(() => 52 { 53 btnTask.Text = i.ToString(); 54 }, Cts.Token, TaskCreationOptions.AttachedToParent, TaskScheduler 55} 56});, cts.Token); 57 } 58 } 59 60 //Button click event 61 private void btnTask_Click(object sender, EventArgs e) 62 { 63 //GoByThread(); 64 GoByTask(); 65 } 66 }

If it is in WPF, traditional methods have changed little code, using Task do not need to modify the code, TaskScheduler.FromCurrentSynchronizationContext (Winform) can get the current thread and WPF thread, and the UpdatText method in the traditional method that looked a bit awkward, Task only need to open a Task in Task.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Allan at November 13, 2013 - 9:34 PM