Basic knowledge of C# multi-threading and its application in Unity

Basic knowledge of C# multi-threading and its application in Unity


Preface: The knowledge contained in multi-threading is rich. As a front-end development, only some basic concepts and usage methods are explained.

concept

what is process

Concept: A process is a running activity of a program in a computer on a certain data set. It is the basic unit of resource allocation and scheduling in the system and the basis of the operating system structure.

To put it simply: opening an application means opening a process on the operating system. The processes can run independently of each other without interfering with each other. The processes can also access and operate each other (for example: I opened the application on my computer. There are two music playing software, one is NetEase Cloud and the other is QQ Music. I have downloaded a song locally. Whether using NetEase Cloud or QQ Music, I can open the song to play or play it at the same time. , this is equivalent to two processes accessing the same file at the same time)

What is a thread

Concept: The smallest unit that the operating system can perform operation scheduling.
It is included in the process and is the actual operating unit in the process. A thread refers to a single sequence of control flow in the process.
In a process Multiple threads can run concurrently. The programs we are currently writing are all in the main thread

A simple understanding of threads: It is a "pipeline" in which code runs from top to bottom.

What is multithreading

Through code, new threads can be opened and multiple "pipes" of code can be run at the same time, which is called multi-threading.

The use of multi-threading

C# comes with a thread class: Thread
Before using it, you need to reference the namespace:

using System.Threading;
  1. Declare a new thread
    First, encapsulate the multi-threaded code that needs to be executed into a custom function. First, write a new thread function and name it NewThread

    public void NewThread()
    {
          
          
         Console.WriteLine("新的线程逻辑");
    }
    

    To declare a new thread is to construct a new class object and put the thread function into the object to initialize it.

    Thread t = new Thread(NewThreadLogic);
    
  2. Start thread

    t.Start();
    

    Executed the code logic in the NewThread function statement block

  3. Set as background thread

    t.IsBackground = true;
    

    Newly opened threads are started as foreground threads by default;
    According to the normal execution sequence, the main thread ends, and all other threads will end with the main thread. And end,
    Assume that other threads are foreground threads, and these thread codes contain infinite loops, then when the main thread ends, the entire process is still
    No It will end because the foreground thread is stuck at the end of the process
    When set as a background thread, if the main thread ends, the background thread will also be forced to end

  4. Close the release thread
    If the opened thread is not an infinite loop and has logic that can be ended, then there is no need to deliberately close it. The code logic will end naturally after the execution of the code logic. If it is an infinite loop, , there are two ways to terminate this thread:

    • If it is an infinite loop thread, changing the value of the Bool variable can shut down the thread. If the Bool condition is not met, the thread will not run.
    while(true) || while(false)
    
    • Syntax off: (not applicable to .Net Core, and lower versions of .Net)
      Stop the thread in the current object through the provided function
    t.Abort();
    

    Or directly empty this thread class object

    t = null;
    
  5. Thread sleep
    Thread.Sleep(1000); Write this code into the thread function, and write that function to sleep that thread
    In milliseconds 1000ms = 1s

Sharing data between threads

  • The memory used by multiple threads is shared because they all belong to the same process. Since multiple threads are executed at the same time, conflicts will occur when accessing the same object
    Problems may occur when multiple threads operate the same memory area at the same time
    Problems can be avoided by locking
//lock
//当我们在多个线程当中想要访问同样的东西 进行逻辑处理时
//为了避免不必要的逻辑顺序执行的差错
//lock(引用类型对象)

while (true)
{
    
    
 //当obj被锁住的时候 如果别的地方obj也被锁住的话 
 //就会先执行别的地方的代码逻辑 等锁住的地方的obj解锁了 也就是锁的地方代码执行完了
 //才会执行下一个锁
 lock (obj)
  {
    
    
   Console.SetCursorPosition(0, 0);
   Console.ForegroundColor = ConsoleColor.Red;
   Console.Write("●");
  }
}

C# multithreading summary

  • Keyword Thread
  • The meaning of multi-threading
    Multi-threading can be used to handle some complex and time-consuming logic
    such as path finding, network communication, etc.
  • For example, there is a complex calculation logic. If it is executed in the main thread (because in a thread, the code is executed from top to bottom), it will cause the main thread to freeze and affect the user experience. Using multiple threads to execute at the same time will improve efficiency. , can be understood as multi-task downloading and parallel downloading of Baidu Netdisk

#Multi-threading in Unity
Unity supports multi-threading, but newly opened threads cannot access the contents of Unity-related objects (MonoBehaviour )
You cannot access any Unity component-related objects in a custom encapsulated multi-threaded function, and an error will be reported. So how to implement multi-threading in this way?

>Idea: We can create a container (it is best to use Queue first in first out to meet the needs), or perform calculations in multiple threads, put the results calculated in multiple threads into the Queue, and then perform calculations in the main thread Just use the calculated result, thus indirectly using multi-threading

Note: Remember to turn off multi-threading in Unity
Because the multi-threading script written in Unity is mounted to the game object in the scene and ends after the game is running. It is still being executed, because Unity itself is a process and is equivalent to symbiosis with Unity

Guess you like

Origin blog.csdn.net/m0_69778537/article/details/134494670