Thread basis will know will be (a)

From the beginning of this article, I will use two articles explain the basics of threads, this article involves the creation of threads , thread waiting , thread suspended , thread termination and thread status detection related content. This article and the next article is the basis for the foundation of the topic, so I will use the example code language and straightforward to explain, in order to be able to follow your other thread just to lay a solid After reading the article, basis. Learning this article you need to have the basic C # language and any version of Microsoft Visual Studio 2015 and above.
The so-called thread, is the operating system uses some way computing unit is divided into a large number of virtual process, then give these virtual processes certain computing power. It should be noted that, since the creation and use is a multithreaded operating system process consumes a lot of resources, so that when there is only a single-core multi-threaded processor cause the operating system to manage these threads are busy, and thus can not run the program and sometimes even the operating system itself It will not work properly (even if the highest priority operating system access to the processor, it still will face this problem). Therefore, the current mainstream processors are multi-core processors and computing power is quite high, but we can not ignore the development of hardware and software improve, the current mainstream of development languages support multithreading. Ado Now we begin the first post-thread basis.

First, create a thread

Ways to create a thread is very simple, we only need to instantiate Thread to, the way we would want to run in the new thread in the instance of the process is passed to the Thread, and then call the start method to run the new thread. Let's look at the code that creates threads.

using System;
using System.Threading;

namespace CreateThread
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread thread = new Thread(PrintNumber);
            thread.Start();
            PrintNumber();
            Console.Read();
        }
        static void PrintNumber()
        {
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine($"第 {i + 1} 个数字是 {i}");
            }
        }
    }
}

The second line of code above the use using namespace Thread introduced where the System.Threading , after we create a static method in the Program class PrintNumber , in this method we write a loop, print out two in the console cycle ten digits. Then we in the Main method instantiates Thread, and in front of the static method, we define the PrintNumber passed as a parameter to the Thread, to note here is that we pass to the Thread is ThreadStart types of parameters, ThreadStart a delegate represents should method performed on a thread, this delegate to the thread constructor, until the call Thread.Start method before calling this method. Finally, we call the Thread Start method to run the newly created thread. Twelfth lines of code we call the PrintNumber method in the usual way, then in order to do the comparison. Then we run the code, you will see two calls PrintNumber method of outputting content will be randomized crossover display.

Mxkaw9.png

Tip:

  1. When we instantiate Thread, ThreadStart or instance ParameterizedThreadStart commission will be passed to the constructor. We only need to specify the method different threads running name, C # compiler will create these objects in the background.
  2. Thread located in the process, a process that contains at least one thread, and there is always a process of a main thread on a mission.

Second, the thread waits

When the program needs to use the results of another thread we need to use Join method, the role of the Join method is to block the calling thread to run, so that the calling thread is waiting for the calling thread (child threads) running after the run is completed. Join method is simply plugging into a sub-thread of the current method call until the child thread is finished. We can use this method to synchronize the steps between the two threads. We look at the use of the following methods through the code to see Join.

using System;
using System.Threading;

namespace ThreadWait
{
    class Program
    {
        static int count = 0;
        static void Main(string[] args)
        {
            Thread thread = new Thread(PrintNumber);
            thread.Start();
            thread.Join();
            PrintNumber();
            Console.WriteLine(count);
            Console.Read();
        }
        static void PrintNumber()
        {
            for (int i = 0; i < 20; i++)
            {
               count+=i;
            }
        }
    }
}

Line 13 in the above code we call the Join method to let the main thread wait because we need to use the results thread thread thread thread running when finished emperor thread will continue to run, the main thread calls in the usual way PrintNumber method, when the count value is not initialized PrintNumber 0, but rather through a thread of execution result of thread 190, via the recalculated PrintNumber, the result is the final output 380. If we do not use the Join method, then the output is not known.

MxeWGR.png

Third, the thread is suspended

For example, when we need to stop Windows service or Kill process (not limited to these two cases), service or process in response to the presence of exit logic, then we can not immediately follow-up on the implementation of the main program code, need to wait for service or process completely out of the rear subsequent code can be performed. But also because the service is stopped or is not the current process procedure Kill the process, we are unable to make the main thread through the Join method waits, then we can use the Sleep method to get the main thread to stop running after a period of time subsequent code (this method is not the best way, we'll just be using it to explain). Sleep method has two overloaded, a unit of milliseconds is passed parameter of type int, parameters, represents a long thread suspended. Another type of overloading is passed TimeSpan parameter, parameter represents the amount of time suspended thread. The following code is to simulate the Kill pause after the city fell into a certain length of time.

using System;
using System.Diagnostics;
using System.Threading;

namespace ThreadPause
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread thread = new Thread(KillProcess);
            thread.Start();
            Console.ReadLine();
        }

        static void KillProcess()
        {
            Process process = Process.GetProcessesByName("notepad")[0];
            process.Kill();
            Thread.Sleep(20);
            if (Process.GetProcessesByName("notepad").Length == 0)
            {
                Console.WriteLine("已被Kill");
            }
        }
    }
}

The above are just simulations, to avoid this is really complicated project. It should be noted that sometimes we will see such wording in the code Thread.Sleep(0), such an approach does not mean pause 0 ms, the fundamental meaning when the parameter value is 0, then the thread will remainder of its time slice to let to anyone ready to run, with the same priority thread. If no other ready to run, with the same priority thread, it will not suspend the execution of the current thread.

Tip:

  1. When the thread is dormant, it will take up as little CPU time.

Fourth, the thread termination

Thread terminates in the actual development with a relatively small, only to use under very special circumstances, according to my experience in project development point of view, I have not encountered a situation need to use thread terminates, let's first look code.

using System;
using System.Threading;

namespace ThreadStop
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread thread = new Thread(PrintNumber);
            thread.Start();
            Thread.Sleep(200);
            thread.Abort();
            Console.Read();
        }
        static void PrintNumber()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine($"第 {i + 1} 个数字是 {i}");
            }
        }

    }
}

The code starts running after calling 200 milliseconds thread Abort method to terminate the thread to continue, we can see the output loop with thread did not completely finished from the figure below, we terminated because the thread is lost. Abort method is equivalent to calling thread into a ThreadAbortException methods cause the thread to be terminated. But here we need to remind you that the procedure for doing so is quite dangerous, because it introduces an exception to this exception can easily destroy your application. And needs to be terminated by the thread processing and call this a Thread.ResetAbort way to refuse to be terminated. I will explain about the way to solve this problem in a later article.

QppCh6.png

Fifth, the thread state is detected

Thread state detection in many cases will be used, the current state of the thread in C # there are ten, these ten states in the table below. Commonly used state had Running , the Unstarted , Stopped and WaitSleepJoin .

status Explanation
Running Thread has been started
StopRequested We are requesting thread stops
SuspendRequested Is requesting thread is suspended
Background Thread is executed as a background thread
Unstarted Thread does not start
Stopped The thread has stopped
WaitSleepJoin The thread is blocked
Suspended Thread Suspended
AbortRequested The thread is stopped
Aborted Thread has been terminated, but the state is not Stopped

The first is the state of the thread Unstarted because this time the thread does not start, when the state becomes the thread starts Running , when we call the Sleep method or Join thread state becomes WaitSleepJoin . Terminate the thread after thread status is Aborted , but there may be AbortRequested . When the thread is finished status will be Stopped .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadState
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread thread = new Thread(PrintNumber);
            Console.WriteLine("线程状态:" + thread.ThreadState);
            thread.Start();
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine("线程状态:" + thread.ThreadState);
            }
        }

        static void PrintNumber()
        {
            for (int i = 0; i < 1000; i++)
            {
                Thread.Sleep(2000);
            }
        }
    }
}

QpC9SK.png

Sixth, work

  1. New multiple threads, respectively, termination and suspension of several processes, and then view their status.

Seven, source code download

Current source code Download:

  1. Address a:
    https://github.com/Thomas-Zhu/Multithreading/tree/master/no1/NoOne
  2. Location of: https://gitee.com/bugback_admin/Multithreading/tree/master/no1/NoOne
Published 204 original articles · won praise 101 · Views 350,000 +

Guess you like

Origin blog.csdn.net/gangzhucoll/article/details/103267544