C # WinForm multithreaded development (a) thread class library

Source: Internet
Author: User
Original address: Click to open the link

[ abstract ] This article describes the C # WinForm multithreaded development of the thread class library, and provides a simple sample code for reference.

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

    • 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.


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 (+);}}}    

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 ThreadS            Tart (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.

The above is the C # WinForm multithreaded development (a) Thread class library content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.