Thread class of multithreading series

In the last article Multithreading Foundation , in this article, let's learn the Thread class in C# inside. The Thread class is in net framework1. API introduced in version 0. If you are not clear about the concept of Thread, please read my last article: Multithreading series (I), multithreading Foundation

In this article, the method code of starting a new thread to call asynchronously is:

        private void DoSomeThing(string btnName) {
            Console.WriteLine($"{btnName} Start, current thread id: {Thread.CurrentThread.ManagedThreadId}");
            long lResult = 0;
            for (long i = 0; i < 1_00_000_000; i++)
                lResult += i;
            Console.WriteLine($"{btnName} End, current thread id: {Thread.CurrentThread.ManagedThreadId}");

How to use Thread to start a new Thread?

Method 1: ParameterizedThreadStart based on delegation

                ParameterizedThreadStart method = o => this.DoSomeThing("btnThread_Click");
                Thread thread = new Thread(method);
                thread.Start();//Start the thread and execute the contents of the delegate

Method 2: ThreadStart based on delegation

                ThreadStart method = () =>
                Thread thread = new Thread(method);
                thread.Start();//Start the thread and execute the contents of the delegate

Thread suspended, suspended, suspended

thread.Suspend();// Pause and suspend the thread. If the thread has been suspended, it will not work

thread.Resume();// Resume a thread that has been suspended

thread.Abort();// When a thread is terminated, an exception will be thrown in the current thread, causing the thread to stop. However, there will be a delay, because the thread belongs to computer resources. If the program wants to stop the thread, it can only notify the operating system (throw an exception), which may not really stop

Thread.ResetAbort();// Terminate the current thread and cancel all requests of the current thread. It can only be terminated once

Thread.Sleep();// How many milliseconds does the current thread sleep before continuing execution

Thread waiting

Method 1: through thread Threadstate gets the state of the current thread

                while (thread.ThreadState != System.Threading.ThreadState.Stopped)
                    Console.WriteLine($"thread _{ thread.ManagedThreadId.ToString("00")}_Running...");

Method 2: wait through Join

thread.Join(); // Wait for the thread to finish executing

thread.Join(5000); // Wait for a limited time, up to 5000 milliseconds

thread priority

thread.Priority = ThreadPriority.Highest;

Set the thread priority as the highest priority: execute first, but it doesn't mean finish first. Even in extreme cases, there are accidents. You can't control the execution order of threads through this

Foreground thread and background thread

thread.IsBackground = false;// The default is false. The foreground thread is closed. The thread needs to be calculated before exiting

thread.IsBackground = true; // Close the process and the thread exits

Thread callback

We want a Thread to trigger another action after executing an action. Here is my Thread callback function encapsulated based on Thread

        /// <summary>
        /// be based on thread Encapsulate a callback and start the child thread to execute the action A--No blocking--A After execution, the child thread will execute the action B,No blocking
        /// </summary>
        /// <param name="method">action A</param>
        /// <param name="action">action B</param>
        private void ThreadWithCallBack(ThreadStart method,Action action)
            ThreadStart threadStart = () =>
            new Thread(threadStart).Start();

Call test code:

        ThreadStart method = () =>
        Action actionCallBack = () =>
            Console.WriteLine("method Callback of");
        this.ThreadWithCallBack(method, actionCallBack);

Gets the return value of the child thread

The following is my function to get the return value of sub threads based on Thread encapsulation

        T t = default(T);
        ThreadStart threadStart = () =>
            t = func.Invoke();
        Thread thread = new Thread(threadStart);

        return new Func<T>(() => {
            return t;

Call test code

        Func<int> func = () => {
            return DateTime.Now.Hour;
        Func<int> funcThread = this.ThreadWithReturn<int>(func);//Non blocking
        int res =  funcThread.Invoke();//block

In the next article, we will continue to talk about thread pools

Tags: Multithreading .NET

Posted by TAViX on Sun, 22 May 2022 10:09:00 +0300