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