【发布时间】:2011-04-11 14:49:12
【问题描述】:
我需要一种方法来停止不包含循环的工作线程。应用程序启动线程,然后线程创建一个 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 - 但我如何实际退出/停止线程?
【问题讨论】:
-
我认为如果你使用BackgrundWorker,你可以将你运行线程的表单中包含的变量设置为true
-
如果可能的话,我想避免重写课程。我已经将其视为其他几个问题的答案 - 我想如果这是正确的做法,我可能不得不这样做。
-
从表面上看,这个问题具体是关于 I/O 并发的取消流程。是这样吗?
-
是的。在更改文件时采取的操作之间,我需要停止线程。
标签: c# multithreading concurrency thread-safety io-completion-ports