C # small example of winform Multithreading

Source: Internet
Author: User

Enter a number in the text box and click "start to accumulate". The program calculates the result from 1 to this number. This accumulation process is time-consuming. If it is directly performed in the UI thread, the current window will be suspended. In order to have a better user experience, the program starts a new thread to execute this computation separately, reads the accumulated results every 200 milliseconds, and displays the results in the label control below the text box. At the same time, the program supports canceling the operation. Click the cancel accumulate button to cancel the accumulate operation and display the current accumulated value to the label. To facilitate the subsequent description, I call the UI thread the main thread and the thread that executes the accumulated computing as the worker thread. This process has two key points:

1: how to access the control created by the main thread in the worker thread;

2: How to cancel time-consuming computing;

To facilitate the call of the accumulate process in the worker thread, I write it as a separate method as follows:

Copy codeThe Code is as follows: // <summary>
/// Accumulate from 1 to the specified value. The CancellationToken parameter is required to enable this method to cancel the operation.
/// </Summary>
/// <Param name = "countid"> specified value accumulated </param>
/// <Param name = "ct"> cancel the credential </param>
Private void countid (int countid, CancellationToken ct ){
Int sum = 0;
For (; countings> 0; countings --){
If (ct. IsCancellationRequested ){
Break;
}
Sum + = countid;
// The Invoke method is used to obtain the context of the thread for creating lbl_Status.
This. Invoke (new Action () => lbl_Status.Text = sum. ToString ()));
Thread. Sleep (200 );
}
}

This method is used to accumulate numbers. It has two points to note.

1: A CancellationToken parameter must be passed to the method to support the cancel operation. (In clr via c #3, this method is called collaborative cancellation. That is to say, an operation must be canceled, and then cancel the operation );

2: to allow the worker thread to access the lbl_Status Control created by the main thread, I use this. Invoke method in this thread. This method is used to obtain access to the control created by the main thread. It requires a delegate as the parameter. In this delegate, we can define the lbl_Status operation. For example, in the above example, I assigned the current accumulate result to the Text attribute of lbl_Status.

Then let's take a look at how to execute computing time-consuming operations in a walking thread, that is, the operation of the "start to accumulate" button:

Copy codeThe Code is as follows: private void btn_Count_Click (object sender, EventArgs e)
{
_ Cts = new CancellationTokenSource ();
ThreadPool. QueueUserWorkItem (state => countings (int. Parse (txt_CountTo.Text), _ cts. Token ));
}

I use a thread pool thread to execute this operation. The reason why I use a thread pool thread instead of my own Threading object is that the thread pool has already created some threads for us by default, this saves some column resource consumption caused by the creation of new threads. After the computing task is completed, the thread pool thread automatically returns to the pool to wait for the next task. I use _ cts as a member variable and declare it as follows:

Copy codeThe Code is as follows: private CancellationTokenSource _ cts;

It needs to introduce using System. Threading; namespace.

The cancellation operation is simpler. The Code is as follows:

Copy codeThe Code is as follows: private void btn_Cancel_Click (object sender, EventArgs e)
{
If (_ cts! = Null)
_ Cts. Cancel ();
}

This completes the example of using multithreading in winform and supports canceling the operation. The complete code is as follows:

Copy codeThe Code is as follows: using System;
Using System. Threading;
Using System. Windows. Forms;

Namespace WinformApp
{
Public partial class Form1: Form
{
Private CancellationTokenSource _ cts;
Public Form1 ()
{
InitializeComponent ();
}

/// <Summary>
/// Accumulate from 1 to the specified value. The CancellationToken parameter is required to enable this method to cancel the operation.
/// </Summary>
/// <Param name = "countid"> specified value accumulated </param>
/// <Param name = "ct"> cancel the credential </param>
Private void countid (int countid, CancellationToken ct ){
Int sum = 0;
For (; countings> 0; countings --){
If (ct. IsCancellationRequested ){
Break;
}
Sum + = countid;
// The Invoke method is used to obtain the context of the thread for creating lbl_Status.
This. Invoke (new Action () => lbl_Status.Text = sum. ToString ()));

Thread. Sleep (200 );
}
}

Private void btn_Count_Click (object sender, EventArgs e)
{
_ Cts = new CancellationTokenSource ();
ThreadPool. QueueUserWorkItem (state => countings (int. Parse (txt_CountTo.Text), _ cts. Token ));
}

Private void btn_Cancel_Click (object sender, EventArgs e)
{
If (_ cts! = Null)
_ Cts. Cancel ();
}

Private void btn_Pause_Click (object sender, EventArgs e)
{

}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.