. 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.