. Net allows the thread to support timeout method instances and Methods destroyed by the thread after execution.

Source: Internet
Author: User


. Net timeout for threads

Use CancellationTokenSource
Copy codeThe Code is as follows:
Private static void TimeoutTest1 ()
{
Var cts = new CancellationTokenSource ();

Var thread = new Thread () =>
{
Console. WriteLine (String. Format ("Thread {0} executing", Thread. CurrentThread. ManagedThreadId ));
Thread. Sleep (10000 );
Console. WriteLine (String. Format ("Thread {0} executing", Thread. CurrentThread. ManagedThreadId ));
});

Cts. Token. Register () =>
{
Thread. Abort ();
});
Cts. CancelAfter (1000 );

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

Console. WriteLine (String. Format ("thread {0} status: {1}", thread. ManagedThreadId, thread. ThreadState ));
}

Here Abort is used to terminate the thread, and CancellationTokenSource also supports other modes. You can go to the official website to check the documentation.

Use Join

Copy codeThe Code is as follows:
Private static void TimeoutTest2 ()
{
Var thread = new Thread () =>
{
Console. WriteLine (String. Format ("Thread {0} executing", Thread. CurrentThread. ManagedThreadId ));
Thread. Sleep (10000 );
Console. WriteLine (String. Format ("Thread {0} executing", Thread. CurrentThread. ManagedThreadId ));
});

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

Console. WriteLine (String. Format ("thread {0} status: {1}", thread. ManagedThreadId, thread. ThreadState ));
}

. Net allows the thread to be destroyed after execution.

The thread is automatically unavailable after execution, unhandled exceptions, and termination. If it is garbage, it will be recycled by GC. One thing to note is: the unhandled exceptions of the thread will lead to application termination, and the exceptions of one thread will not automatically bubble to other threads.

 

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.