Reputation: 4161
I was wondering how do I test that the code I was running actually begun in the same time...
Here's a piece of code:
var threads = new List<Thread>
{
new Thread(() => Call1stFunc()),
new Thread(() => Call2ndFunc())
}
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
How do I unit test it and verify that the thread's executed in the same time?
If my code is wrong how I would know what is the correct code to execute such task?
Upvotes: 2
Views: 7153
Reputation: 182
You can't start threads at exactly same time and the order of execution is not determined. But you can use synchronization constructs to synchronize you threads. For instance, use ManualResetEventSlim to force your threads to wait until it set.
For unit testing you can use thread number and time marker. Just store them in List and then compare start times with delta.
static void Main(string[] args)
{
var ids = new[] { "1", "2", "3" };
var manualResetEventSlim = new ManualResetEventSlim();
foreach (var id in ids)
{
var thread = new Thread((obj) =>
{
Console.WriteLine(string.Format("thread {0} strated", obj as string));
manualResetEventSlim.Wait();
Console.WriteLine("thread {0} work in progress", obj as string);
});
thread.Start(id);
}
Console.ReadKey();
manualResetEventSlim.Set();
Console.ReadKey();
}
Upvotes: 3