Ok so I have a fairly simple question which I could not find a concise answer for. I am wondering if i need to worry about calling a lock()
statement when reading the elapsed property of a Stopwatch
while it is still running.
Also is a Stopwatch
what I should be using to measure run-times of a thread. I have read in other similar questions a DispatchTimer
could be used. I have also looked into using events, however that seemed like a lot of overhead for something so simple, please inform me if that is just plain wrong and I should be using events. Some simple code to illustrate what I am talking about.
class foo
{
private bool _isRunning { get; set; }
private Stopwatch sw { get; set; }
public void StartThread()
{
this._isRunning = true;
new Thread(new ThreadStart(this.DoWork)).Start();
this.sw.Restart();
}
public void StopThread()
{
this._isRunning = false;
this.sw.Stop();
}
private void DoWork()
{
while(this._isRunning)
{
//Do Stuff
}
}
public TimeSpan GetRuntime()
{
return this.sw.Elapsed;
}
public foo()
{
_isRunning = false;
sw = new Stopwatch();
}
}
Say in an application using the above class I were to call GetRuntime()
from a different thread before I stop the Stopwatch
would I need to add a lock()
statement to ensure that I get the correct data, and that I wont be blocking the Stopwatch
from continuing to run. Or am i correct in thinking that it does not need a lock()
and will be fine as is.
I do understand that you can theoretically run as many reads as you would like, I am just curious seeing as the Elapsed properties backing store is constantly being written to if that changed things or not. I have read a lot of information about thread safety, but I am just looking for a clarification and confirmation I am indeed thinking about this correctly.