.net讓線程支持超時
使用 CancellationTokenSource
復制代碼 代碼如下:
private static void TimeoutTest1()
{
var cts = new CancellationTokenSource();
var thread = new Thread(() =>
{
Console.WriteLine(String.Format("線程{0}執行中", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(10000);
Console.WriteLine(String.Format("線程{0}執行中", Thread.CurrentThread.ManagedThreadId));
});
cts.Token.Register(() =>
{
thread.Abort();
});
cts.CancelAfter(1000);
thread.Start();
thread.Join();
Console.WriteLine(String.Format("線程{0}的狀態:{1}", thread.ManagedThreadId, thread.ThreadState));
}
這裡采用了 Abort 終止了線程,CancellationTokenSource 也支持其它模式,可以去官方看看文檔。
使用 Join
復制代碼 代碼如下:
private static void TimeoutTest2()
{
var thread = new Thread(() =>
{
Console.WriteLine(String.Format("線程{0}執行中", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(10000);
Console.WriteLine(String.Format("線程{0}執行中", Thread.CurrentThread.ManagedThreadId));
});
thread.Start();
thread.Join(1000);
thread.Abort();
Console.WriteLine(String.Format("線程{0}的狀態:{1}", thread.ManagedThreadId, thread.ThreadState));
}
.net讓線程在執行結束後銷毀
線程執行完、遇到未處理異常和被終止後就自動不可用了,如果是垃圾,自然會被 GC 給回收,有一點需要說明的是:線程的未處理異常會導致應用程序的終止,一個線程的異常不會自動冒泡到其它線程。