我需要一种方法来停止不包含循环的工作线程。应用程序启动线程,然后线程创建一个 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 - 但我如何实际退出/停止线程?
最佳答案
我建议使用 ManualResetEvent
,而不是 bool 标志。线程启动 FileSystemWatcher
,然后等待一个事件。当调用 Stop
时,它会设置事件:
private ManualResetEvent ThreadExitEvent = new ManualResetEvent(false);
public void Start()
{
// set up the watcher
this.CreateFileWatch();
// then wait for the exit event ...
ThreadExitEvent.WaitOne();
// Now tear down the watcher and exit.
// ...
}
public void Stop()
{
ThreadExitEvent.Set();
}
这样您就不必使用计时器,而且您仍会收到所有通知。
关于c# - 退出没有循环的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5623113/