The use of C# thread Thread

introduction

In the C# programming language, threads are a concurrent execution mechanism that can execute multiple tasks at the same time, improving the efficiency and responsiveness of the program. C# provides the Thread class to handle thread-related operations. This article will introduce in detail the usage and precautions of the Thread class in C#.
Insert image description here



Basic concepts of threads

Before we start exploring the use of threads in C#, let's first understand some basic concepts related to threads.
Insert image description here

Thread

A thread is the smallest unit of operating system scheduling and represents an independent execution sequence. A process can contain multiple threads, each thread has its own execution path and execution status.

Multithreading

Multithreading refers to the simultaneous execution of multiple threads in a program. Multithreading can be used to implement parallel computing, asynchronous operations, etc.

Main Thread

The main thread is the entry thread of the program and is responsible for executing the main logic of the program. In C#, the Main() method runs on the main thread.

Background Thread

Background threads are threads that do not prevent the program from exiting. The background thread is automatically stopped immediately when all foreground threads (including the main thread) end.


Create and start threads

In C#, threads can be created and started through the Thread class. The following are the basic steps to create and start a thread using the Thread class:

  1. Create a Thread object: By instantiating the Thread class, you can create a new thread object.
Thread thread = new Thread(ThreadMethod);
  1. Define thread method: Define a method as the execution body of the new thread. Thread methods are executed in a new thread.
void ThreadMethod()
{
    
    
    // 线程执行的代码逻辑
}
  1. Start a thread: Start the execution of a new thread by calling the Start() method.
thread.Start();

Here's a complete example:

using System;
using System.Threading;

class Program
{
    
    
    static void Main()
    {
    
    
        // 创建并启动新线程
        Thread thread = new Thread(ThreadMethod);
        thread.Start();

        // 在主线程中执行其他任务
        for (int i = 0; i < 5; i++)
        {
    
    
            Console.WriteLine($"Main Thread: {
      
      i}");
            Thread.Sleep(1000);
        }
    }

    static void ThreadMethod()
    {
    
    
        for (int i = 0; i < 5; i++)
        {
    
    
            Console.WriteLine($"Worker Thread: {
      
      i}");
            Thread.Sleep(1000);
        }
    }
}

In the above example, we created and started the thread by creating a Thread object and passing in a method as a parameter. By calling the Start() method, the new thread begins executing the code in the ThreadMethod() method, while the main thread continues to perform other tasks.


Thread synchronization

In multi-threaded programming, since multiple threads accessing shared resources at the same time may cause race conditions and data inconsistencies, a thread synchronization mechanism needs to be used to ensure correct coordination between multiple threads. Here are some commonly used thread synchronization methods:

  • lock keyword: Ensure that only one thread can access shared resources by adding a lock in the code block.
lock (lockObject)
{
    
    
    // 访问共享资源的代码逻辑
}
  • Monitor class: Use the Enter() and Exit() methods of the Monitor class to define the critical section in the code block to ensure that only one thread can enter the critical section.
Monitor.Enter(lockObject);
try
{
    
    
    // 访问共享资源的代码逻辑
}
finally
{
    
    
    Monitor.Exit(lockObject);
}
  • Mutex class: Use the WaitOne() and ReleaseMutex() methods of the Mutex class to define a mutex lock in the code block to ensure that only one thread can acquire the mutex lock.
Mutex mutex = new Mutex();
mutex.WaitOne();
try
{
    
    
    // 访问共享资源的代码逻辑
}
finally
{
    
    
    mutex.ReleaseMutex();
}
  • Semaphore class: Use the WaitOne() and Release() methods of the Semaphore class to implement the thread's waiting and notification mechanism.
Semaphore semaphore = new Semaphore(0, 1);
semaphore.WaitOne();
try
{
    
    
    // 访问共享资源的代码逻辑
}
finally
{
    
    
    semaphore.Release();
}

Manage threads

C# provides some methods and properties for managing threads to help us better control and manage thread execution. The following are some commonly used methods and properties:

  • Join() method: wait for a thread to complete execution.
thread.Join();
  • Sleep() method: suspends the execution of the current thread for a period of time.
Thread.Sleep(milliseconds);
  • Abort() method: terminates the execution of a thread.
thread.Abort();
  • IsAlive attribute: Determine whether the thread is active.
if (thread.IsAlive)
{
    
    
    // 线程正在执行
}

Insert image description here


Summarize

This article introduces in detail the use of the Thread class in C# to handle thread-related operations. By creating and starting threads, we can achieve parallel execution of multiple tasks and improve the efficiency and responsiveness of the program. At the same time, the thread synchronization mechanism helps us ensure the correct coordination of shared resources in a multi-threaded environment. In addition, C# also provides many methods and properties for managing thread execution.

Guess you like

Origin blog.csdn.net/qq_22120623/article/details/135105724