C# multithreading


Release date:2023-09-07 Update date:2023-10-13 Editor:admin View counts:165

Label:

C# multithreading

A thread is defined as the execution path of the program. Each thread defines a unique control flow. If your application involves complex and time-consuming operations, it is often beneficial to set different thread execution paths, and each thread performs specific work.

Threads are lightweight processes. A common example of using threads is the implementation of parallel programming in modern operating systems. Using threads saves the waste of CPU cycles and improves the efficiency of the application.

The program we have written so far runs as a single process of a single thread as a running instance of the application. However, in this way the application can only perform one task at a time. In order to perform multiple tasks simultaneously, it can be divided into smaller threads.

Thread life cycle

The thread life cycle begins with System.Threading.Thread when an object of the class is created, it ends when the thread is terminated or execution is completed.

The various states in the thread life cycle are listed below:

  • Unstarted state: The condition when a thread instance is createdbut the Start method is not called.

  • Ready state: what happens when a thread is ready to run and wait for a CPU cycle.

  • Unrunnable state: threads are not runnable in the following situations:

    • Sleep method has been called

    • Wait method has been called

    • Blocking by I/O operation

  • Death status: the condition when the thread has finished execution or aborted.

Main thread

In C# System.Threading.Thread class is used for thread work. It allows you to create and access a single thread in a multithreaded application. Thefirst thread to be executed in a process is called the main thread.

When the C# program starts execution, the main thread is created automatically. Use Thread class is called by a child thread of the mainthread. You can use the Thread analogous CurrentThread property to access the thread.

The following program demonstrates the execution of the main thread:

Example

using System;
using System.Threading;

namespace MultithreadingApplication
{
    class MainThreadProgram
    {
        static void Main(string[] args)
        {
            Thread th = Thread.CurrentThread;
            th.Name = "MainThread";
            Console.WriteLin+e("This is {0}", th.Name);
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

This is MainThread

Powered by TorCMS (https://github.com/bukun/TorCMS).