1、創建線程
Thread thread = new Thread(new ThreadStart(SortAscending));
2、啟動線程
thread.Start();
3、終止線程
如果想要一個進程結束,一種方法是讓線程的入口函數執行完畢,但是在很多情況你下這種方式並不足以滿足應用程序的需求。
1)Abort
當Abort方法被調用,它會向要終止的線程觸發ThreadAbortException,然後線程被終止。示例如下:
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(Run);
thread.Start();
Thread.Sleep(1000);
thread.Abort();
Console.WriteLine("Aborted.");
Console.ReadLine();
}
static void Run()
{
try
{
Console.WriteLine("Run executing.");
Thread.Sleep(5000);
Console.WriteLine("Run completed.");
}
catch (ThreadAbortException ex)
{
Console.WriteLine("Caught thread abort exception.");
}
}
}
運行結果如圖:
2) Join
join方法阻塞調用線程直到指定的線程停止執行。
static void Main(string[] args)
{
Thread thread = new Thread(Run);
thread.Start();
Thread.Sleep(1000);
thread.Join();
Console.WriteLine("Joined.");
Console.ReadLine();
}
www.2cto.com
static void Run()
{
try
{
Console.WriteLine("Run executing.");
Thread.Sleep(5000);
Console.WriteLine("Run completed.");
}
catch (ThreadAbortException ex)
{
Console.WriteLine("Caught thread abort exception.");
}
}
}
運行結果: