Home  >  Article  >  Backend Development  >  Detailed explanation of Thread class for multi-threading in C#

Detailed explanation of Thread class for multi-threading in C#

零下一度
零下一度Original
2017-06-23 16:51:424802browse

Use the System.Threading.Thread class to create and control threads.

Commonly used constructors are:

        // 摘要: //     初始化 System.Threading.Thread 类的新实例,指定允许对象在线程启动时传递给线程的委托。//// 参数: //   start://     System.Threading.ParameterizedThreadStart 委托,它表示此线程开始执行时要调用的方法。//// 异常: //   System.ArgumentNullException://     start 为 null。        [SecuritySafeCritical]public Thread(ParameterizedThreadStart start);//// 摘要: //     初始化 System.Threading.Thread 类的新实例。//// 参数: //   start://     System.Threading.ThreadStart 委托,它表示此线程开始执行时要调用的方法。//// 异常: //   System.ArgumentNullException://     start 参数为 null。        [SecuritySafeCritical]public Thread(ThreadStart start);

1. Create a thread without parameters

ThreadStart delegate defines a parameterless method with a return type of void.

        public void Main()
        {
            Thread vThread = new Thread(ThreadFun);//vThread.Name = "td_Name";  // 线程名称vThread.Start(); //开始执行线程Console.WriteLine("This is the main thread:id=" + Thread.CurrentThread.ManagedThreadId);
        }void ThreadFun() // 来自委托:ThreadStart         {
            Console.WriteLine("Running in a new thread:id=" + Thread.CurrentThread.ManagedThreadId);for (int i = 0; i < 10; i++)
            {
                Console.Write(".");
                Thread.Sleep(500);
            }
            Console.WriteLine("THREAD END");
        }

Output result:

Replace ThreadFun() in the appeal code with Lambda expression , becomes a simple way to use Thread:

        public void Main()
        {
            Thread vThread = new Thread(() =>{
                Console.WriteLine("Running in a new thread");});//vThread.Name = "td_Name";  // 线程名称vThread.Start(); //开始执行线程Console.WriteLine("This is the main thread");
        }

## 2. Pass parameters to the thread

Two ways: one is to construct Thread using method parameters with

ParameterizedThreadStart delegate; the other is to create a custom class and put the thread The method is defined as an instance method, so that the instance data is initialized first and then the thread is started.

For example: passing parameters

        public struct TdData // 传递数据        {public string Message;  //数据string字段}
Use the first method:

        public void Main()
        {
            TdData tData = new TdData() { Message = "Thread Info" };
            Thread vThread = new Thread(ThreadFun);
            vThread.Start(tData);   // 开始执行线程,传递参数Console.WriteLine("This is the main thread");
        }void ThreadFun(object pObj) // 来自委托:ParameterizedThreadStart         {
            TdData vData = (TdData)pObj;
            Console.WriteLine("In a new thread, Received:{0}", vData.Message);            
        }
Use the first method Two ways: first customize a class.

    public class TdHelper
    {public TdData mData; // 传递数据// 构造函数public TdHelper(TdData pData)
        {this.mData = pData;
        }public void ThreadFun() // 来自委托:ThreadStart         {
            Console.WriteLine("In a new thread, TdDataMessage:{0}", mData.Message);
        }
    }
Then, create Thread in the main thread (where needed) and use the instance method

TdHelper.ThreadFun() as a parameter of the constructor.

        public void Main()
        {
            TdData tData = new TdData() { Message = "Thread Info" };
            TdHelper tHelper = new TdHelper(tData); // 传递参数Thread vThread = new Thread(tHelper.ThreadFun);
            vThread.Start();
            Console.WriteLine("This is the main thread");
        }

3. Background thread

By default, the thread created by the Thread class is a foreground thread, and the threads in the thread pool are always background threads. As long as there is one foreground thread running, the application process is running. If multiple foreground threads are running and the Main() method ends, the application is still active until all foreground threads complete their tasks.

You can make it a background thread by setting the

IsBackground attribute of the Thread class instance;

        public void Main()
        {
            Thread vThread = new Thread(() =>{
                Console.WriteLine("New thread started");  // Title3Thread.Sleep(5000);
                Console.WriteLine("New thread completed"); // Title2});//vThread.IsBackground = true;            vThread.Start();
            Console.WriteLine("This is the main thread"); // Title1}

When the IsBackground property defaults to false, you can see the complete 3 sentences of output information on the console; but if it is set to true, you will not wait until the third sentence When 3 pieces of information (Title2) are output, the main thread Main() has completed execution, and the console window is automatically closed.

4. Thread priority

Through the Priority attribute, you can adjust the priority of the Thread class instance. The default is: vThread.Priority = ThreadPriority.Normal; // Enumeration value

Relationship: Highest > AboveNormal > Normal > BelowNormal > Lowest

5. Control thread

Call the Start() method of the Thread object to create a thread. However, after calling the Start() method, the new thread is still not in the Running state, but in the Unstarted state. The thread will change to the Running state only if the operating system's thread scheduler chooses to run the thread. Through the Thread.ThreadState property, you can get the current state of the thread.

Using the Thread.Sleep() method will put the thread in the WaitSleepJoin state. After the time period defined by the Sleep() method, the thread will wait to be scheduled by the operating system again.

To stop a thread, you can call the Thread.Abort() method. Calling this method will throw a ThreadAbortException in the thread that receives the termination command. Use a handler to catch this exception, and the thread can complete some cleanup work before ending. A thread can also continue working after receiving a ThreadAbortException exception as the result of calling the Thread.Abort() method. If the thread terminates without reset, the status of the thread that received the termination request changes from AbortRequested to Aborted.

If you want to wait for the thread to end, you can call the Thread.Join() method, which will stop the current thread and set it to the WaitSleepJoin state until the joined thread completes.

See:

[]

The above is the detailed content of Detailed explanation of Thread class for multi-threading in C#. For more information, please follow other related articles on the PHP Chinese website!

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