Question

I have a method that performs some work. I use a System.Diagnostics.Stopwatch in that method to measure the time taken to execute the task performed by that method. This method is called several times by multiple threads as follows:

ArrayList workerThreads = new ArrayList();  

     for (int i = 0; i < numThread; i++)
        {
            Thread workerThread = new Thread(DoWork);
            workerThread.IsBackground = true;
            workerThreads.Add(workerThread);
        }

for (int i = 0; i < numThread; i++)
            {                   
                ((Thread)workerThreads[i]).Start();
            }

public void DoWork()
{
    Stopwatch sw = Stopwatch.StartNew();
    // Do something
    sw.Stop();
    Log.Info(sw.ElapsedMilliseconds);

}

Is it thread safe to use Stopwatch the way I am? Will the results be accurate or do I need to explicitly lock it so the threads won't step over each other's values of Elapsed time there?

Was it helpful?

Solution

There are no thread safety concerns involved, because you are not sharing instance of Stopwatch across threads.

In theory Stopwatch.StartNew could be thread unsafe, but it is not:

Any public static (Shared in Visual Basic) members of this type are thread safe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top