.NET ez 2012-05-04
Thread並沒有內建超時自動結束的功能,所以利用Join等待的特性,再利用Abort來結束Thread。
using System;
using System.Threading;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(delegate()
{
Console.WriteLine("Thread開始");
Thread.Sleep(3000); //等待3秒
Console.WriteLine("Thread結束");
}));
t.Start();
Console.WriteLine("Thread等待");
if (!t.Join(2000)) t.Abort(); //超過兩秒結束Thread
Console.WriteLine("程式結束");
Console.ReadLine();
}
}
}標籤: .NET
