The Thread class has more control over threads in the thread pool. This class allows creating foreground threads, setting thread priority, etc. The constructor of the Thread class is overloaded to accept delegate parameters of ThreadStart and ParameterizedThreadStart types.
1. Pass data to threads
There are two ways to pass data to threads:
1. Use the Thread constructor with ParameterizedThreadStart delegate parameters:
//Define a data type and pass it to the threadpublic struct Data { public string Message; } //Create a method to give the method to the ParameterizedThreadStart delegate of the threadstatic void ThreadMainWithParameters(object obj) { Data d = (Data)obj; ("Running in a thread, received {0}", ); } static void Main() { Data d = new Data { Message = "Info" };//Create a data instance Thread t2 = new Thread(ThreadMainWithParameters);//Create a thread (d);//Start the thread and pass parameters}
2. Customize a class, define the thread's method as an instance method, and then start the thread after initializing the instance's data.
//Define a class to store the data required by the thread and the method of thread startuppublic class MyThread { private string data;//Thread data public MyThread(string data) { = data; } //Thread start method public void ThreadMain() { ("Running in a thread, data: {0}", data); } } static void Main() { MyThread obj = new MyThread("info");//Create instance information Thread t3 = new Thread();//Start the instance method (); }
2. Background thread
If there is any foreground thread running in the application, the application is running. The thread created by the Thread class is the foreground thread by default, and the thread created in the thread pool is the background thread. When creating threads using the Thread class, you can set the IsBackground property to set whether the background thread or the foreground thread is created when the Thread thread is created. For example:
//Create a thread method to call in the main threadstatic void ThreadMain() { ("Thread {0} started", ); (3000); ("Thread {0} completed", ); } static void Main() { Thread t1 = new Thread(ThreadMain); = "MyNewThread"; (); (100); ("Main thread ending now..."); /************************ Output*************************** * Thread MyNewThread started * Main thread ending now... * Thread MyNewThread completed *************************************************/ }
As you can see, the main thread completes the task first. However, the new thread started in the main thread is the foreground thread (default), causing the new thread to still write to the console output after the main thread ends the task. If the thread's IsBackground property is set to true before the thread starts, the execution of the new thread will be terminated (regardless of completing the task or not) when the main thread ends.
static void Main() { Thread t1 = new Thread(ThreadMain); = "MyNewThread"; = true; (); (100); ("Main thread ending now..."); /******************Output************************ * Thread MyNewThread started * Main thread ending now... *************************************************/ }
Background threads are suitable for completing background tasks.
3. Priority of threads
Threads are scheduled by the operating system. Assigning priority to threads will affect the thread scheduling order. The higher the priority thread, the system will be scheduled to run on the CPU. If the thread is waiting for the resource, it stops running and frees the CPU.
Possible reasons why threads must wait: responding to sleep instructions, waiting for disk I/O to complete, waiting for network packets to arrive, etc. If the thread does not actively release the CPU, the thread scheduler will preempt the thread. A thread consists of a time amount, which can continue to use the CPU until the time arrives (if there is no higher priority thread). If multiple threads with the same priority are waiting for the CPU, the thread scheduler will use a loop scheduling principle to hand over the CPU to threads one by one. If the thread is preempted by other threads, it will queue until the end.
Only when multiple threads with the same priority are running at the same time can the amount of time and loop rules be used. Priority is dynamic: if a thread is CPU-intensive, always needs a CPU, and does not wait for resources, its priority will be reduced to the basic priority defined by the thread; if a thread is waiting for resources, its priority will be increased. Due to the increase in priority, the thread may get the CPU at the end of the next wait.
The Priority property of a thread can set the priority of the thread. When a thread specifies a priority, it may reduce the probability of running other threads. Therefore, priority can be changed briefly as needed.
4. Control threads
Calling the Start() method of the Thread object can create a thread. However, the new thread does not come from the Running state, but from the Unstarted state. When the thread scheduler calls the thread, the thread will change to the Running state. Its ThreadState property can obtain the state of the thread.
The static method of the thread class Sleep() will put the thread in the WaitSleepJoin state. After waiting for a period of time, the thread will be awakened again.
If you want to stop a thread, you can call the method Abort(). Calling this method will throw a ThreadAbortException type exception in the thread that receives the termination command. To catch this exception, you can do some cleaning work before the thread ends. If the method ResetAbort() is called again, there may be a chance to continue running after receiving the exception. If the thread is not reset, the state of the thread that received the terminated request will be changed from AbortRequested to Aborted.
Calling the Join() method can wait for the end of the thread. This method stops the current thread and sets it to the WaitSleepJoin state until the joined thread is completed.
The above is a detailed explanation of the usage of the c# Thread class. For more information about the c# Thread class, please follow my other related articles!