C # multithreaded Development 5: Thread abort and Interrupt methods

Source: Internet
Author: User

Use the thread's Abort method to terminate the thread, while the thread's interrupt method can only break the thread in the WaitSleepJoin state, and the thread resumes execution when the thread state is no longer waitsleepjoin. Calling the Abort method on a thread throws an ThreadAbortException exception, and calling the interrupt method throws a ThreadInterruptedException exception.

The following example demonstrates the use of the abort and interrupt methods.

Using system;using system.threading; Namespace abortandinterruptexp{class Program {static void Main (string[] args) {CONSOLE.W            Riteline ("------------interrupt method of Implementation---------------");            thread T1 = new Thread (DoWork); T1.            Start ();            Thread.Sleep (1000); T1.             Interrupt (); T1.             Join ();            Console.WriteLine ("------------Abort Method implementation---------------");            Thread t2 = new Thread (DoWork); T2.            Start ();            Thread.Sleep (1000); T2.        Abort ();                } static void DoWork () {for (int i = 0; i <; i++) {try {Console.WriteLine ("+ i +" loops.)                    ");                Thread.Sleep (500); } catch (ThreadInterruptedException e) {Console.WriteLine ("the" + i + "loop , the thread is interrupted and the next loop thread continues to run.                "); } catch (ThreadabortexcEption e) {Console.WriteLine ("the" + i + "loop, the thread is terminated and the thread will not continue to run"); }            }        }    }}

The instance results are shown below.

As you can see from the results, when the thread state is waitsleepjoin , The interrupt method can be used to break threads when the thread state is no longer WaitSleepJoin , the thread will continue to execute, and the thread after the Abort method terminates will no longer execute.

C # multithreaded Development 5: Thread abort and Interrupt methods

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.