Detailed explanation of examples of C# thread control

零下一度
Release: 2017-06-23 16:34:03
Original
2199 people have browsed it

Option 1:

Call the thread control method. Start:Thread.Start();Stop:Thread. Abort();Pause:Thread.Suspend();Continue:Thread.Resume();

        private void btn_Start_Click(object sender, EventArgs e)
        {
            mThread.Start();  // 开始        }private void btn_Stop_Click(object sender, EventArgs e)
        {
            mThread.Abort();  // 终止        }private void btn_Suspend_Click(object sender, EventArgs e)
        {
            mThread.Suspend();  // 暂停        }private void btn_Resume_Click(object sender, EventArgs e)
        {
            mThread.Resume();  // 继续}
Copy after login

The thread is 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);
                }
            });
Copy after login

It is worth noting: Threads that are stopped by Thread.Abort() (or end by themselves) thread), cannot be started again directly through the Thread.Start() method, and a thread must be re-created to start.

So, the "Start Button" event should be:

        private void btn_Start_Click(object sender, EventArgs e)
        {// 定义线程mThread = new Thread(() => // Lambda 表达式            {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();  // 开始}
Copy after login

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

#Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. (Thread.Suspend has been deprecated. Please use other thread classes in the system, such as monitors, mutexes, events, and semaphores, to synchronize threads or protect resources.)Because it is impossible to determine what code the thread is executing when it is currently suspended. If the thread holding the lock is suspended during security permissions evaluation, other threads in the AppDoamin may be blocked. If you suspend a thread while it is executing the constructor, other threads in the AppDomain that try to use the class will be blocked. This is prone to deadlock.

Option 2: Determine whether to continue at an appropriate position during the thread running process (such as after a complete function/command) 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; // 返回false,线程停止            }else if (this.mTdFlag == 2)
            {while (mTdFlag != 1)
                {
                    Thread.Sleep(200); // 假暂停;停顿时间越短,越灵敏if (this.mTdFlag == 3)
                    {return false; // 返回false,线程停止                    }
                }
            }return true; // 返回true,线程继续}
Copy after login
3. Modify the control command event:

        private void btn_Stop_Click(object sender, EventArgs e)
        {this.mTdFlag = 3;//mThread.Abort();  // 终止        }private void btn_Suspend_Click(object sender, EventArgs e)
        {this.mTdFlag = 2;//mThread.Suspend();  // 暂停        }private void btn_Resume_Click(object sender, EventArgs e)
        {this.mTdFlag = 1;//mThread.Resume();  // 继续}
Copy after login
4. In the thread Appropriate position during the running process to determine whether the thread continues

            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()) // 返回 false 则,停止                            {break;//return;                            }
                        }this.textBox1.Text += string.Format("{0} => vSum = {1}\r\n", DateTime.Now.ToString(), vSum);if (!WaitForContinue()) // 返回 false 则,停止                        {break;// return;                        }
                        Thread.Sleep(1000);
                    }
                }catch (ThreadAbortException ex)
                {
                    Console.WriteLine("ThreadAbortException:{0}", ex.Message);this.textBox1.Text += ex.Message + "...";
                }finally{this.textBox1.Text += "线程已结束";
                }
            });
Copy after login

In the form, solve the problem of cross-thread access:

In the form constructor Add code: Control.CheckForIllegalCrossThreadCalls = false;

[]

The above is the detailed content of Detailed explanation of examples of C# thread control. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template