C # winform multithreading (1)

Source: Internet
Author: User

Windows is a multitasking system. If you are using Windows 2000 or later, you can view the programs and processes running on the current system through the task manager. What is a process? When a program starts to run, it is a process that refers to the memory and system resources used by the running programs and programs. A process is composed of multiple threads. A thread is an execution stream in a program, and each thread has its own proprietary register (Stack pointer, program counter, etc ), but the code zone is shared, that is, different threads can execute the same function. Multithreading means that a program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks.

1. Thread description

In. NET Framework class library, all classes related to multithreading applications are stored in the system. Threading namespace. The thread class is used to create threads, and the threadpool class is used to manage thread pools. In addition, it provides a mechanism to solve actual problems such as thread execution arrangements, deadlocks, and inter-thread communication. If you want to use multithreading in your application, you must include this class. The thread class has several important methods, which are described as follows:
Start (): Start the thread
Sleep (INT): a static method that pauses the specified number of milliseconds of the current thread.
Abort (): This method is usually used to terminate a thread.
Suspend (): This method does not terminate the unfinished thread. It only suspends the thread and can be recovered later.
Resume (): resume the execution of threads suspended by the suspend () method

The thread entry tells the program what to do with this thread. in C #, the thread entry is provided through the threadstart proxy (delegate). You can regard threadstart as a function pointer, point to the function to be executed by the thread. after the start () method, the thread starts to execute the Functions Represented or pointed to by threadstart. Threadstate may take the following values in various situations:
Aborted: the thread has stopped.
Abortrequested: The thread. Abort () method of the thread has been called, but the thread has not stopped.
Background: The thread is executed in the background, which is related to the attribute thread. isbackground.
Running: The thread is running normally.
Stopped: the thread has been stopped.
Stoprequested: The thread is being requested to stop
Suincluded: the thread has been suspended. (In this status, you can call resume () to run the thread again)
Suspendrequested: The thread is requesting to be suspended, but cannot respond.
Unstarted: thread. Start () is not called to start the thread.
Waitsleepjoin: The thread is blocked because it calls methods such as wait (), sleep (), and join ().

Thread used in winform

The most direct method is also supported in. NET 1.0. However, please note that this method is already an incorrect method after. NET 2.0.

Code
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Private void form1_load (Object sender, eventargs E)
{
Thread thread = new thread (threadfuntion );
Thread. isbackground = true;
Thread. Start ();
}
Private void threadfuntion ()
{
While (true)
{
This. textbox1.text = datetime. Now. tostring ();
Thread. Sleep (1000 );
}
}
}

 

This code throws an exception in vs2005 or 2008: Cross-thread operation not valid: Control 'textbox1' accessed from a thread other than the thread it was created on. this is because. NET 2.0 and later enhanced the security mechanism, and does not allow direct cross-thread access to control attributes in winform. So how can we solve this problem? Several solutions are provided below.

Solution 1: Set control. checkforillegalcrossthreadcils to false when the thread is created. This code tells the compiler: in this class, we do not check whether the cross-thread call is legal (if this sentence is not added, the operation is not abnormal, it indicates that the system and the default mode are not checked ). However, this method is not advisable. We can view the definition of the checkforillegalcrossthreadcils attribute and find that it is static. That is to say, no matter where the value is modified in the project, it will take effect globally. In addition, we usually check whether cross-thread access is abnormal. If someone else in the project modifies this attribute, our solution fails and we have to adopt another solution.

Solution 2

Code
Namespace testinvoker
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}

Private void button#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 above-mentioned Code, we can see that the problem has been solved. By waiting for Asynchronization, we will not always hold the control of the main thread, in this way, you can control winform multi-threaded controls without cross-thread call exceptions.

Related Article

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.