The interrupt method of C#thread

Source: Internet
Author: User

Interrupt method, you can only break a thread that is in the WaitSleepJoin state, and the thread resumes execution when the thread is not waitsleepjoin.

Calling the interrupt method produces a threadinterruptexception exception

    Class Program {static void Main (string[] args) {Stayawake stayawake = new Stayawake (
            );
            Thread newthread = new Thread (new ThreadStart (Stayawake.threadmethod));
            Newthread.start ();
            Newthread.name = "New Thread";
            Newthread.interrupt ();

            Console.WriteLine ("Main thread calls interrupt on new thread");
            Stayawake.sleepswitch = true;
            Console.WriteLine ("1stat" + Thread.CurrentThread.ThreadState);
        Newthread.join ();

        } class Stayawake {bool Sleepswitch = false;
            public bool Sleepswitch {set {Sleepswitch = value; }} public void Threadmethod () {Console.WriteLine () ' New thread ' is executing thread me
            Thod ");
            while (!sleepswitch) {thread.spinwait (10000000);
        } try    {Console.WriteLine ("2name" + Thread.CurrentThread.Name);
                Console.WriteLine ("2stat" + Thread.CurrentThread.ThreadState);
                Console.WriteLine ("New thread going to sleep");
            Thread.Sleep (Timeout.infinite); catch (ThreadInterruptedException e) {Console.WriteLine ("New thread can not go"
            To sleep-"+" interrupted by main thread "); }
        }
    }




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.