我需要一种方法来停止不包含循环的工作线程。应用程序启动线程,然后线程创建一个FileSystemWatcher对象和一个Timer对象。其中每一个都有回调函数。到目前为止我所做的是向线程类添加一个volatile bool成员,并使用计时器来检查这个值。一旦设置了这个值,我就挂断了如何退出线程。
protected override void OnStart(string[] args)
{
try
{
Watcher NewWatcher = new Watcher(...);
Thread WatcherThread = new Thread(NewWatcher.Watcher.Start);
WatcherThread.Start();
}
catch (Exception Ex)
{
...
}
}
public class Watcher
{
private volatile bool _StopThread;
public Watcher(string filePath)
{
this._FilePath = filePath;
this._LastException = null;
_StopThread = false;
TimerCallback timerFunc = new TimerCallback(OnThreadTimer);
_ThreadTimer = new Timer(timerFunc, null, 5000, 1000);
}
public void Start()
{
this.CreateFileWatch();
}
public void Stop()
{
_StopThread = true;
}
private void CreateFileWatch()
{
try
{
this._FileWatcher = new FileSystemWatcher();
this._FileWatcher.Path = Path.GetDirectoryName(FilePath);
this._FileWatcher.Filter = Path.GetFileName(FilePath);
this._FileWatcher.IncludeSubdirectories = false;
this._FileWatcher.NotifyFilter = NotifyFilters.LastWrite;
this._FileWatcher.Changed += new FileSystemEventHandler(OnFileChanged);
...
this._FileWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
...
}
}
private void OnThreadTimer(object source)
{
if (_StopThread)
{
_ThreadTimer.Dispose();
_FileWatcher.Dispose();
// Exit Thread Here (?)
}
}
...
}
因此,当线程被告知停止时,我可以处理 Timer / FileWatcher - 但是我如何实际退出/停止线程?