Thread Control of C# Multithreading

Keywords: C# Lambda

Programme 1:

Start: Thread.Start(); Stop: Thread.Abort(); Stop: Thread.Suspend(); Continue: Thread.Resume();

 

        private void btn_Start_Click(object sender, EventArgs e)
        {
            mThread.Start();  // start
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            mThread.Abort();  // termination
        }

        private void btn_Suspend_Click(object sender, EventArgs e)
        {
            mThread.Suspend();  // suspend
        }

        private void btn_Resume_Click(object sender, EventArgs e)
        {
            mThread.Resume();  // Continue
        }

Threads are defined as:

            mThread = new Thread(() =>
            {
                try
                {
                    for (int j = 0; j < 20; j++)
                    {
                        int vSum = 0;
                        this.textBox1.Text += "--->";
                        for (int i = 0; i < 100000000; i++)
                        {
                            if (i % 2 == 0)
                            {
                                vSum += i;
                            }
                            else
                            {
                                vSum -= i;
                            }
                        }
                        this.textBox1.Text += string.Format("{0} => vSum = {1}\r\n", DateTime.Now.ToString(), vSum);
                        Thread.Sleep(1000);
                    }
                }
                catch (ThreadAbortException ex)
                {
                    Console.WriteLine("ThreadAbortException: {0}", ex.Message);
                }
            });

It is worth noting that threads that stop through Thread.Abort() or run on their own cannot be started again directly through Thread.Start(), and a thread must be created to start again.

So the "Start Button" event should be:

        private void btn_Start_Click(object sender, EventArgs e)
        {
            // Define threads
            mThread = new Thread(() => // Lambda Expression
            {
                try
                {
                    for (int j = 0; j < 20; j++)
                    {
                        int vSum = 0;
                        this.textBox1.Text += "--->";
                        for (int i = 0; i < 100000000; i++)
                        {
                            if (i % 2 == 0)
                            {
                                vSum += i;
                            }
                            else
                            {
                                vSum -= i;
                            }
                        }
                        this.textBox1.Text += string.Format("{0} => vSum = {1}\r\n", DateTime.Now.ToString(), vSum);
                        Thread.Sleep(1000);
                    }
                }
                catch (ThreadAbortException ex)
                {
                    Console.WriteLine("ThreadAbortException: {0}", ex.Message);
                }
            });

            mThread.Start();  // start
        }

In addition, for the Thread.Suspend() and Thread.Resume() methods, Microsoft has marked them as obsolete:

Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protection resources. http://go.microsoft.com/fwlink/?linkid=14202 (Thread.Suspend has been rejected). Use other types of threads in the system, such as monitors, mutexes, events and semaphores, to synchronize threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202)

Because it is impossible to determine what code the thread is executing when it is currently suspended. If a thread holding a lock is suspended during security permission evaluation, other threads in AppDoamin may be blocked. If it is suspended while the thread is executing the constructor, other threads attempting to use this class in AppDomain will be blocked. This is prone to deadlock.

Programme II:

Determine whether to continue threads at an appropriate location (such as after a complete function/command) during the running of a thread, and then determine the fate of the thread.

1. Define a global variable:

Int mTdFlag = 0; //1: normal operation; 2: pause; 3: stop

2. Define a judgment method:

        bool WaitForContinue()
        {
            if (this.mTdFlag == 3)
            {
                return false; // Return false,Thread stop
            }
            else if (this.mTdFlag == 2)
            {
                while (mTdFlag != 1)
                {
                    Thread.Sleep(200); // Holiday pause; the shorter the pause time, the more sensitive it is
                    if (this.mTdFlag == 3)
                    {
                        return false; // Return false,Thread stop
                    }
                }
            }
            return true; // Return true,Thread Continuation
        }

3. Modify Control Command Events:

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            this.mTdFlag = 3;
            //mThread.Abort();  // termination
        }

        private void btn_Suspend_Click(object sender, EventArgs e)
        {
            this.mTdFlag = 2;
            //mThread.Suspend();  // suspend
        }

        private void btn_Resume_Click(object sender, EventArgs e)
        {
            this.mTdFlag = 1;
            //mThread.Resume();  // Continue
        }

4. Judging whether the thread continues or not at the appropriate place in the running process of the thread

            mThread = new Thread(() =>
            {
                try
                {
                    for (int j = 0; j < 20; j++)
                    {
                        int vSum = 0;
                        this.textBox1.Text += "--->";
                        for (int i = 0; i < 100000000; i++)
                        {
                            if (i % 2 == 0)
                            {
                                vSum += i;
                            }
                            else
                            {
                                vSum -= i;
                            }
                            if (i % 10000000 == 0)
                            {
                                this.textBox1.Text += ".";
                            }
                            if (!WaitForContinue()) // Return false Then, stop
                            {
                                break;
                                //return;
                            }
                        }
                        this.textBox1.Text += string.Format("{0} => vSum = {1}\r\n", DateTime.Now.ToString(), vSum);
                        if (!WaitForContinue()) // Return false Then, stop
                        {
                            break;
                            // return;
                        }
                        Thread.Sleep(1000);
                    }
                }
                catch (ThreadAbortException ex)
                {
                    Console.WriteLine("ThreadAbortException: {0}", ex.Message);
                    this.textBox1.Text += ex.Message + "...";
                }
                finally
                {
                    this.textBox1.Text += "Thread has ended";
                }
            });

 

In the form, solve the cross-threaded access problem: add code to the form constructor: Control.CheckForIllegalCrossThreadCalls = false;

 

[http://www.cnblogs.com/CUIT-DX037/]

Posted by Jackount on Mon, 24 Jun 2019 12:04:37 -0700