. NET methods to allow the thread to support timeouts and how to destroy them at the end of execution _ practical tips

Source: Internet
Author: User
Tags sleep


. NET let thread support timeout

Using CancellationTokenSource

Copy Code code as follows:

private static void TimeoutTest1 ()
{
var cts = new CancellationTokenSource ();

            var thread = new Thread (() =>
             {
                 Console.WriteLine (String.Format ("thread {0} execution", THREAD.CURRENTTHREAD.MANAGEDTHREADID));
                Thread.Sleep ( 10000);
                Console.WriteLine (String.Format ("thread {0} in execution", Thread.CurrentThread.ManagedThreadId));
           });

Cts. Token.register (() =>
{
Thread. Abort ();
});
Cts. Cancelafter (1000);

Thread. Start ();
Thread. Join ();

Console.WriteLine (String.Format (state of thread {0}: {1}), Thread. Managedthreadid, Thread. ThreadState));
}

This uses Abort to terminate the thread, and CancellationTokenSource also supports other modes that can go to the official to see the document.

Use Join

Copy Code code as follows:

private static void TimeoutTest2 ()
{
var thread = new Thread (() =>
{
Console.WriteLine (String.Format ("thread {0} in execution", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep (10000);
Console.WriteLine (String.Format ("thread {0} in execution", Thread.CurrentThread.ManagedThreadId));
});

Thread. Start ();
Thread. Join (1000);
Thread. Abort ();

Console.WriteLine (String.Format (state of thread {0}: {1}), Thread. Managedthreadid, Thread. ThreadState));
}

. NET lets threads destroy after execution ends

The thread executes, encounters an unhandled exception, and is automatically unavailable after it is terminated, and if it is garbage, it is naturally recycled by GC, and one thing to note is that the unhandled exception of the thread causes the application to terminate, and the exception of one thread does not automatically bubble to another thread.

 

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.