c#無限循環線程如何正確退出
在主程序將要結束時,迅速正確退出無限循環執行的子線程。一般子線程循環執行會有一個指定的周期,
在子線程等待(或者睡眠)時,無法喚醒退出,尤其在執行周期較長時,子線程無法即刻退出,導致
程序無法迅速關閉。
1. 定義AutoReset
private AutoResetEvent exitEvent;
exitEvent = new AutoResetEvent(false);
此事件作為線程即將退出的信號,初始化為false。
2. 定義線程循環周期(睡眠周期)
int waitTime;
3. 定義線程執行
private void Process()
{
while (true)
{
Console.WriteLine("do some thing");
if (exitEvent.WaitOne(waitTime))
{
break;
}
}
}
在執行函數每次均等待退出信號若干時間,若沒有退出信號則繼續執行,若收到退出信號則立即退出。
可以避免使用sleep長時間睡眠無法立即退出。
4. 定義線程退出方法
public void Stop()
{
exitEvent.Set();
thread.Join();
}
全部代碼
線程類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace threadexit
{
class ThreadA
{
private AutoResetEvent exitEvent;
private Thread thread;
private int waitTime;
public ThreadA(int time)
{
exitEvent = new AutoResetEvent(false);
waitTime = time;
thread = new Thread(new ThreadStart(Process));
}
public void Run()
{
thread.Start();
}
public void Stop()
{
exitEvent.Set();
thread.Join();
}
private void Process()
{
while (true)
{
Console.WriteLine("do some thing");
if (exitEvent.WaitOne(waitTime))
{
break;
}
}
}
}
}
主函數
static void Main(string[] args)
{
var t = new ThreadA(3000);
t.Run();
System.Threading.Thread.Sleep(10000);
Console.WriteLine(DateTime.Now.ToShortTimeString() + "begin stop thread");
t.Stop();
Console.WriteLine(DateTime.Now.ToShortTimeString() + "thread stoped");
Console.ReadKey();
}
