Examples of C # threading controls

Source: Internet
Author: User
Tags terminates thread stop
programme One:

Invokes the thread control method. Start:Thread.Start (); Stop:Thread.Abort (); Suspension:Thread.Suspend (); Continuation: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 ();  Terminates        }private void Btn_suspend_click (object sender, EventArgs e)        {            mthread.suspend ();  Pause        }private void Btn_resume_click (object sender, EventArgs e)        {            mthread.resume ();  Continue to

Thread definitions are:

            Mthread = new Thread (() =>{try{for (int j = 0, J <; J + +)                    {int vSum = 0;this.textbox1.text + = "--->"; for (i NT 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 (+);                    }                } catch (ThreadAbortException ex)                {                    Console.WriteLine ("Threadabortexception:{0}", ex. Message);                }            );

It is important to note that a thread that is stopped by Thread.Abort () (or a thread that runs its own end) cannot be started directly through the Thread.Start () method, and a thread must be re-created.

Therefore, the Start button event should be:

 private void Btn_start_click (object sender, EventArgs e) {//define thread Mthre AD = new Thread (() =//Lambda expression {try{for (int j = 0; J <; J + +) {int vSum = 0;th                            Is.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 ("Threadabortexcept ION:{0} ", ex.                Message);            }            });  Mthread.start (); Start} 

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

Thread.Suspend has been deprecated. Classes in System.Threading, such as Monitor, mutexes, Event, and Semaphore, to synchronize Threads or prot ECT resources. (Thread.Suspend has been rejected.) Use other class threads in the system such as monitors, mutexes, events, and semaphores to synchronize threads or protect resources. )

Because, it is not possible to determine what code it is executing when the thread is currently suspended. If the thread holding the lock is suspended during security privilege evaluation, other threads in the appdoamin may be blocked. If the thread is suspending it while it is executing the constructor, other threads in the AppDomain that try to use the class will be blocked. Such a deadlock can occur easily.

Scenario Two:

Determine if you want to continue the thread, and then determine the thread's fate, in the appropriate location (such as after a complete function/command) during the course run.

1. Define a global variable:

int mtdflag = 0; //1: normal operation, 2: Pause, 3: Stop

2. Define a method of judgment:

        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, shorter pause time, more sensitive if (This.mtdflag = = 3)                    {return false;//return Fals E, thread Stop                    }                }            }return true; Returns TRUE, Thread continues}

3. Modify the control command event:

        private void Btn_stop_click (object sender, EventArgs e)        {this.mtdflag = 3;//mthread.abort ();  Terminates        }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 to

4. Determine whether the thread continues in the appropriate location during the process

            Mthread = new Thread (() =>{try{for (int j = 0; J <; J + +) {int vSum = 0;this.textbo X1.                            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 to stop {Break;//return; }}this.textbox1.text + = string. Format ("{0} = VSum = {1}\r\n", DateTime.Now.ToString (), vSum);                        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 is Over"; }            });

In the form, resolve cross-thread access issues: Add code in the form constructor: Control.checkforillegalcrossthreadcalls = false;

[]

Related Article

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.