C#Thread Learning Note 1: Thread Foundation

Posted by howard-moore on Wed, 27 Nov 2019 21:30:01 +0100

This note was taken from: https://www.cnblogs.com/zhili/archive/2012/07/18/Thread.html And record the learning process for future reference.

Introduction to threads

A process is a collection of resources to be used by instances of an application, each running in its own process to ensure that the application is not affected by other applications.

Threads are the basic unit of execution in a process, and a process can contain multiple threads.The first thread executed at the process entry is the main thread of a process. In a.Net application, the Main() method is used as the entry to the program (the thread is the unit of execution of the process, and the process is a container for the thread).

2. Thread Scheduling and Priority

Windows is called a preemptive multithreaded operating system because a thread can be preempted at any time and another thread can be scheduled.

Each thread is assigned a priority from 0 to 31. The system first assigns high priority threads to the CPU for execution.

Windows supports seven relative thread priorities: Idle, Lowest, Below Normal, Normal, Above Normal, Highest, and Time-Critical.Normal is the default thread priority, but Thread's Priority property can be set in programs to change thread priority.

It is of the ThreadPriority enumeration type: Lowest, BelowNormal, Normal, AboveNormal, and Highest, and the CLR maintains the Idle and Time-Critical priorities for itself.

The list of enumerated values is as follows:

Member Name Explain
Lowest Thread can be placed after other priority threads.
BelowNormal Thread can be placed after the Normal priority thread before the Lowest priority thread.
Normal

Thread can be placed after the AboveNormal priority thread before the BelowNormal priority thread.

By default, threads are placed at Normal priority.

AboveNormal Thread can be placed after the Highest priority thread before the Normal priority thread.
Highest Thread can be placed before other priority threads.

3. Foreground and background threads

Threads in.Net are divided into foreground and background threads:

I. The main thread is executed at the beginning of the program. If you need to create a thread again, the thread you create is the child thread of the main thread. It is the foreground thread.(

II. Subthreads can be foreground or background threads.

III. The foreground thread must execute completely, and the process will survive even if the main thread shuts down.

IV. When all foreground threads stop running, the CLR forces the end of any background threads that are still running. These background threads are terminated directly without throwing exceptions.

V. The only difference between foreground and background threads is that background threads do not prevent process termination and can be modified to background threads at any time.

        /// <summary>
        /// Foreground and background threads
        /// </summary>
        private static void ThreadType()
        {
            //Create a new thread(Default to foreground thread)
            Thread backThread = new Thread(Worker)
            {
                //Change Thread to Background Thread
                IsBackground = true
            };

            //adopt Start Method Start Thread
            backThread.Start();

            //If backThread Is the foreground thread, the application will not terminate until 5 seconds.
            //If backThread Is a background thread, the application terminates immediately.
            Console.WriteLine("It's from main thread.");
            //Console.Read();
        }

        private static void Worker()
        {
            //5 seconds rest
            Thread.Sleep(5000);
            Console.WriteLine("It's from worker thread.");
        }

If you leave IsBackground = true, but want to continue executing the Worker() method, you can call the thread.Join() method to implement it.The Join() method guarantees that the main thread (foreground thread) will not run until the asynchronous thread (background thread) has finished running.

        static void Main(string[] args)
        {
            ThreadTypeUseJoin();
        }

        /// <summary>
        /// Foreground and background threads use Join()Method
        /// Join()Method ensures that the main thread (foreground thread) is asynchronous thread(Background threads) run after completion
        /// </summary>
        private static void ThreadTypeUseJoin()
        {
            //Create a new thread(Default to foreground thread)
            Thread backThread = new Thread(Worker)
            {
                //Change Thread to Background Thread
                IsBackground = true
            };

            //adopt Start Method Start Thread
            backThread.Start();
            backThread.Join();

            Console.WriteLine("It's from main thread.");
            Console.Read();
        }

        private static void Worker()
        {
            //5 seconds rest
            Thread.Sleep(5000);
            Console.WriteLine("It's from worker thread.");
        }

The results are as follows:

4. Use of simple threads

In fact, when the foreground and background threads were introduced above, a thread was created by ThreadStart delegation, and a multithreaded process has been implemented.

The following multithreading is achieved by the ParameterizedThreadStart delegation:

        static void Main(string[] args)
        {
            ThreadTypeUseParameterized();
        }

        /// <summary>
        /// Foreground and background threads(Use ParameterizedThreadStart Delegate for multithreading)
        /// </summary>
        private static void ThreadTypeUseParameterized()
        {
            //Create a new thread(Default to foreground thread)
            Thread backThread = new Thread(new ParameterizedThreadStart(Worker1));

            //adopt Start Method Start Thread
            backThread.Start(123);

            //If backThread Is the foreground thread, the application will not terminate until 5 seconds.
            //If backThread Is a background thread, the application terminates immediately.
            Console.WriteLine("It's from main thread.");
        }

        private static void Worker1(object parameter)
        {
            //5 seconds rest
            Thread.Sleep(5000);
            Console.WriteLine(parameter+" is from worker1 thread.");
            Console.Read();
        }

The results are as follows:

Topics: C# REST Windows