Thread Safe Method with a Stop Watch
I'm trying to determine if my code I'm using is Thread Safe or not. I'm
basically trying to call a method several times from different threads,
and capture the time it takes for certain calls within the method to
complete.
Here is an example of what I am doing.
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace ThreadTest
{
class Program
{
static BlockingCollection<TimeSpan> Timer1 = new
BlockingCollection<TimeSpan>(new ConcurrentBag<TimeSpan>());
static TimeSpan CaptureTime(Action action)
{
Stopwatch stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.Elapsed;
}
static void ThreadFunction()
{
TimeSpan timer1 = new TimeSpan();
timer1 = CaptureTime(() =>
{
//Do Some Work
});
Timer1.Add(timer1);
}
static void Main(string[] args)
{
for (int i = 0; i < 50; i++)
{
var task = new Task(ThreadFunction);
task.Start();
}
}
}
}
And what I'm trying to determine is whether or not the TimeSpan values
returned by the CaptureTime method can be trusted.
Thank you to anyone who can enlighten me.
No comments:
Post a Comment