I have an object in a worker thread, which I can instruct to stop running. I can implement this using a bool or an AutoResetEvent:
boolean:
private volatile bool _isRunning;
public void Run() {
while (_isRunning)
{
doWork();
Thread.Sleep(1000);
}
}
AutoResetEvent:
private AutoResetEvent _stop;
public void Run() {
do {
doWork();
} while (!_stop.WaitOne(1000));
}
The Stop()
method would then set _isRunning
to false, or call _stop.Set()
.
Apart from that the solution with AutoResetEvent may stop a little faster, is there any difference between these method? Is one "better" than the other?
C# volatile does not provide all the guaranties. It may still read stale data. Better to use underlying OS synchronisation mechanism as it provides much stronger guaranties.
All this in great depth discussed by Eric Lippert (really worth reading), here is short quote: