C # multi-thread control,

Source: Internet
Author: User

C # multi-thread control,

Solution 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 (); // Start} private void btn_Stop_Click (object sender, EventArgs e) {mThread. abort (); // terminate} private void btn_Suspend_Click (object sender, EventArgs e) {mThread. suspend (); // pause} private void btn_Resume_Click (object sender, EventArgs e) {mThread. resume (); // continue}

The thread is defined:

            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: Through Thread. the Thread (or self-running end Thread) that Abort () stops cannot directly pass through the Thread. start () method to Start again. You must create a new thread to Start it.

Therefore, the "Start button" event should be:

Private void btn_Start_Click (object sender, EventArgs e) {// defines the Thread 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, Microsoft has marked Thread. Suspend () and Thread. Resume () methods 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 protect resources. The http://go.microsoft.com/fwlink? Linkid = 14202 (Thread. SuspendRejected. Use other threads in the system, such as monitors, mutex, events, and semaphores, to synchronize threads or protect resources. Http://go.microsoft.com/fwlink? Linkid = 14202)

Because it cannot determine what code it is executing when the thread is currently suspended. If the lock-holding thread is suspended during security permission evaluation, other threads in AppDoamin may be blocked. If the constructor is suspended when the thread is executing the constructor, other threads trying to use the class in the AppDomain will be blocked. This is prone to deadlocks.

Solution 2:

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

1. define a global variable:

Int mTdFlag = 0; // 1: normal operation; 2: paused; 3: stopped

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); // false pause; the shorter the pause time, the more sensitive if (this. mTdFlag = 3) {return false; // return false, thread stop }}return true; // return true, thread continues}

3. Modify the control command event:

Private void btn_Stop_Click (object sender, EventArgs e) {this. mTdFlag = 3; // mThread. abort (); // terminate} private void btn_Suspend_Click (object sender, EventArgs e) {this. mTdFlag = 2; // mThread. suspend (); // pause} private void btn_Resume_Click (object sender, EventArgs e) {this. mTdFlag = 1; // mThread. resume (); // continue}

4. Check whether the thread continues when the thread is running properly.

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 () // if false is returned, stop {break; // return ;}} this. textBox1.Text + = string. format ("{0 }=> vSum = {1} \ r \ n", DateTime. now. toString (), vSum); if (! WaitForContinue () // if false is returned, stop {break; // return;} Thread. sleep (1000) ;}} catch (ThreadAbortException ex) {Console. writeLine ("ThreadAbortException: {0}", ex. message); this. textBox1.Text + = ex. message + "... ";} finally {this. textBox1.Text + = "the thread has ended ";}});

 

Solve the cross-thread access problem in the form: add the code in the form constructor: Control. checkforillegalcrossthreadcils = false;

 

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.