C # WinForm Multithreading (i) Thread class library

Source: Internet
Author: User

Windows is a multitasking system, and if you are using Windows 2000 and later, you can view the programs and processes that are running on the current system through Task Manager. What is a process? When a program starts running, it is a process that refers to the memory and system resources that are used by the programs and programs that are running. And a process is composed of multiple threads, the thread is an execution flow in the program, each thread has its own proprietary registers (stack pointers, program counters, etc.), but the code area is shared, that is, different threads can execute the same function. Multithreading refers to a program that contains multiple execution streams, in which multiple different threads can be run concurrently to perform different tasks, that is, allowing a single program to create multiple threads of parallel execution to accomplish their tasks.

A description of thread

In the. NET Framework class library, all classes related to multithreaded application are placed in the System.Threading namespace. The thread class is provided for creating threads, the ThreadPool class is used to manage the thread pool, and so on, and also provides a mechanism for solving practical problems such as thread execution scheduling, deadlock, and inter-thread communication. If you want to use multi-threading in your application, you must include this class. The thread class has several critical methods, which are described below:
Start (): Start thread
Sleep (int): Static method, pauses the number of milliseconds specified by the current thread
Abort (): This method is typically used to terminate a thread
Suspend (): This method does not terminate an unfinished thread, it simply suspends the thread and can be resumed later.
Resume (): Restore the execution of a thread that was suspended by the suspend () method

The thread entry lets the program know what to do with this thread, in C #, the thread entry is provided through the ThreadStart Proxy (delegate), and you can interpret ThreadStart as a function pointer to the function that the thread is going to execute when calling Thread.Start () method, the thread begins executing the function that ThreadStart represents or points to. The possible values of threadstate in various cases are as follows:
Aborted: Thread has stopped
AbortRequested: The thread's Thread.Abort () method has been called, but the thread has not stopped
Background: Thread is executed in the background, related to property thread.isbackground
Running: Thread is running correctly
Stopped: Thread has been stopped
Stoprequested: Thread is being requested to stop
Suspended: Thread has been suspended (in this state, it can be rerun by calling the Resume () method)
Suspendrequested: Thread is asking to be suspended but not responding
Unstarted: The run of the thread started without calling Thread.Start ()
WaitSleepJoin: Thread is blocked because it calls wait (), Sleep (), or join ()

Thread used in two WinForm

The first thing you can do is look at the most straightforward method, which is supported under. NET 1.0. Note, however, that this method is already a bad way after. NET 2.0.

Code

This code throws an exception on VS2005 or 2008: cross-thread operation not Valid:control ' textBox1 ' accessed from a thread other than the thre Ad it was created on. This is because. NET 2.0 strengthens security mechanisms and does not allow the control's properties to be accessed directly across threads in WinForm. So how to solve this problem, here are a few scenarios.

The first scenario: set the Control.checkforillegalcrossthreadcalls to false on thread-created gas. This code tells the compiler that in this class we do not check whether a cross-thread invocation is legal (and if there is no exception to this statement, then the system and default are not checked). However, this method is not advisable. When we look at the definition of this attribute of Checkforillegalcrossthreadcalls, we find that it is static, which means that no matter where we modify the value in the project, he will work on the global. And like this cross-thread access is an exception, we usually check it out. If someone else in the project modifies this property, then our scenario fails and we have to take another approach.

Second scenario


Namespace Testinvoker
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}

private void Button1_Click (object sender, EventArgs e)
{
Thread thread = new Thread (new ThreadStart (Startsomeworkfromuithread));
Thread. IsBackground = true;
Thread. Start ();
Startsomeworkfromuithread ();
Label1. Text = "Set value through another thread!";
}

private void Startsomeworkfromuithread ()
{
if (this. invokerequired)
{
BeginInvoke (New EventHandler (runsonworkerthread), null);
}
Else
{
Runsonworkerthread (this, null);
}
}

private void Runsonworkerthread (object sender, EventArgs e)
{
Thread.Sleep (2000);
Label1. Text = System.DateTime.Now.ToString ();
}
}
}


Through the code, you can see that the problem has been solved, by waiting for the asynchronous, we will not always hold the control of the main thread, so that can not occur in the case of cross-thread call exception to complete multi-threaded WinForm multi-line program control.

C # WinForm Multithreading (i) Thread class library

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.