Whats the best way to unit test from multiple threads? Whats the best way to unit test from multiple threads? multithreading multithreading

Whats the best way to unit test from multiple threads?


In .NET, ThreadPool threads won't return without setting up ManualResetEvents or AutoResetEvents. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such.

Something I have found that works is

  1. Create an array of threads.
  2. Setup the ThreadStart method of each thread.
  3. Start each thread.
  4. Join on all threads (blocks the current thread until all other threads complete or abort)
public static void MultiThreadedTest(){    Thread[] threads = new Thread[count];    for (int i = 0; i < threads.Length; i++)    {        threads[i] = new Thread(DoSomeWork());    }    foreach(Thread thread in threads)    {        thread.Start();    }    foreach(Thread thread in threads)    {        thread.Join();    }}


@ajmastrean, since unit test result must be predictable we need to synchronize threads somehow. I can't see a simple way to do it without using events.

I found that ThreadPool.QueueUserWorkItem gives me an easy way to test such use cases

 ThreadPool.QueueUserWorkItem(x => {     File.Open(fileName, FileMode.Open);    event1.Set(); // Start 2nd tread;    event2.WaitOne(); // Blocking the file;});ThreadPool.QueueUserWorkItem(x => {     try    {        event1.WaitOne(); // Waiting until 1st thread open file        File.Delete(fileName); // Simulating conflict    }    catch (IOException e)    {        Debug.Write("File access denied");    }});


Your idea should work fine. Basically you just want to spawn a bunch of threads, and make sure the ones writing the file take long enough to do it to actually make the readers wait. If all of your threads return without error, and without blocking forever, then the test succeeds.