参见MSDN:http://msdn.microsoft.com/zh-cn/library/7a2f3ay4.aspx
使用一个标示位来判断线程何时终止,而不是使用Abort(强行终止线程,即使线程尚未完成任务)方法。
实例代码如下:
using System;
using System.Collections.Generic;
using System.Threading;
public class MyClass
{
public static void Main()
{
Console.WriteLine("Main thread is start");
ThreadTest threadTest = new ThreadTest();
Thread childThread = new Thread(threadTest.Work);
childThread.Start();
for(int i=0;i<10000;i++)
{
if(i%50 == 0)
{
Console.WriteLine("Main thread is running");
}
}
threadTest.StopThread();
childThread.Join();
Console.WriteLine("Main thread is stop");
Console.Read();
}
}
public class ThreadTest
{
private volatile bool _threadStop;
/// <summary>
/// 执行内容
/// </summary>
public void Work()
{
Console.WriteLine("Child thread is start");
while(_threadStop == false)
{
Console.WriteLine("Child thread is running");
}
Console.WriteLine("Child thread is stop");
}
/// <summary>
/// 停止线程
/// </summary>
public void StopThread()
{
_threadStop = true;
}
}