I need a way to stop a worker thread that does not contain a loop. The application starts the thread, the thread then creates a FileSystemWatcher object and a Timer object. Each of these has callback functions. What I have done so far is add a volatile bool member to the thread class, and use the timer to check this value. I'm hung up on how to exit the thread once this value is set.
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 (?)
}
}
...
}
So I can dispose the the Timer / FileWatcher when the thread is told to stop - but how do I actual exit/stop the thread?
Rather than a Boolean flag, I would suggest using a ManualResetEvent. The thread starts the FileSystemWatcher, then waits on an event. When Stop is called, it sets the event:
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();
}
This prevents you from having to use a timer, and you'll still get all your notifications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With