Most of the time, you can use the traditional method to implement Winform asynchronous operations, but I personally feel that the Code is not easy to understand and it is a little uncomfortable to use. You can also use tasks to implement tasks (. the newly added object in net4.0 is actually an encapsulation of the thread pool thread, which has many functions and better operations. I will not talk about anything else. Today I will only talk about asynchronous operations, here is a simple example:
First, click the Go button. The number is automatically increased, which is relatively simple.
Directly run the Code:
CancellationTokenSource cts = ; taskScheduler = UpdateText( ( btnTask.Invoke( Action<> btnTask.Text = Thread thread = Thread(() => ( i = ; ; i++ Thread.Sleep( 34 (cts == cts = Task.Factory.StartNew(() => ( i = ; ; i++ Thread.Sleep( Task.Factory.StartNew(() => btnTask.Text = btnTask_Click( }
If it is in WPF, the traditional method has to change the code, but the Task does not need to modify the code, TaskScheduler. fromCurrentSynchronizationContext () can be used to obtain the current Winform thread or WPF thread. In the traditional method, the UpdatText method seems awkward. You only need to enable another Task in the Task by using the Task.