Home  >  Article  >  Backend Development  >  C# WinForm multi-thread development (1) Thread class library

C# WinForm multi-thread development (1) Thread class library

黄舟
黄舟Original
2017-02-20 10:56:321836browse

Original address: Click to open the link

[Abstract]This article introduces C# Thread class library for WinForm multi-thread development, and provides simple sample code for reference.

Windows is a multi-tasking system. If you are using Windows 2000 and above, you can use Task Manager View the programs and processes currently running on the system. What is a process? When a program starts running, it is a process. The process refers to the running program and the memory and system resources used by the program. A process is composed of multiple threads. A thread is an execution flow in the program. Each thread has its own private register (stack pointer, program counter, etc.), but the code area is shared, that is, different Threads can execute the same function. Multithreading means that a program contains multiple execution streams, that is, multiple different threads can be run simultaneously in one program to perform different tasks, which means that a single program is allowed to create multiple parallel execution threads to complete their respective tasks.

1 A note about Thread

In the .net framework class library, all classes related to multi-threading mechanism applications are placed in the System.Threading namespace. It provides the Thread class for creating threads, the ThreadPool class for managing thread pools, etc. In addition, it also provides mechanisms to solve practical 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 crucial methods, which are described as follows:

  • Start(): Start the thread

  • Sleep(int): Static method, pauses the current thread for the specified number of milliseconds

  • Abort(): Usually use this method To terminate a thread

  • Suspend(): This method does not terminate the unfinished thread, it only suspends the thread and can be resumed later.

  • Resume(): Resume the execution of the thread suspended by the Suspend() method

Thread The entrance allows the program to know what to let this thread do. In C#, the thread entrance is provided through the ThreadStart delegate. You can understand ThreadStart as a function pointer, pointing to the function to be executed by the thread. When calling Thread.Start () method, the thread begins to execute the function represented or pointed to by ThreadStart. The possible values ​​of ThreadState in various situations are as follows:

  • Aborted: The thread has stopped

  • AbortRequested: The Thread.Abort() method of the thread has been called, but the thread has not stopped yet

  • Background: The thread is in Background execution, related to the property Thread.IsBackground

  • Running: The thread is running normally

  • Stopped: The thread has been stopped

  • StopRequested: The thread is being asked to stop

  • Suspended: The thread has been suspended (in this state, it can be re-run by calling the Resume() method)

  • SuspendRequested: The thread is requesting to be suspended, but will not respond in time

  • ##Unstarted: Thread.Start() is not called to start the running of the thread

  • ##WaitSleepJoin:

    The thread is in a blocked state because it calls methods such as Wait(), Sleep() or Join()


Two threads used in Winform

First of all, you can look at the most direct method, which is also the method supported under .net 1.0. But please note that this method is already a wrong method 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(1000);
        }
    }
}

This code throws an exception on 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 the security mechanism has been strengthened after .net 2.0 and does not allow direct cross-thread access to the properties of the control in winform. So how to solve this problem? Here are several solutions.


The first option: Set Control.CheckForIllegalCrossThreadCalls to false when Thread is created. This code tells the compiler: In this class, we do not check whether cross-thread calls are legal (if there is no exception when running without adding this sentence, it means that the system adopts the non-checking method by default). However, this approach is not advisable. When we look at the definition of the CheckForIllegalCrossThreadCalls property, we will find that it is static, which means that no matter where we modify this value in the project, it will take effect globally. And we usually check whether there are exceptions in such cross-thread access. If others in the project modify this attribute, then our solution will fail and we will need to adopt another solution.

Second solution

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 above code, you can see that the problem has been solved By waiting for asynchronous, we will not always hold the control of the main thread, so that multi-threaded control of the winform multi-threaded control can be completed without cross-thread call exceptions.


The above is the content of C# WinForm multi-thread development (1) Thread class library. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn