In unit tests, you often need to perform simple verification on [ThreadStatic] and processing of some mutex environments. There are many ways to start parallel processing. Here is a simple method.
Code Static void Parallel (params ThreadStart [] actions)
{
List <Thread> threads = actions. Select (a => new Thread (a). ToList ();
Threads. ForEach (t => t. Start ());
Threads. ForEach (t => t. Join ());
}
The following is a complete example:
Code Using System. Collections. Generic;
Using System. Linq;
Using System. Threading;
Using System. Diagnostics;
Using Microsoft. VisualStudio. TestTools. UnitTesting;
Namespace VisionLogic. Training. ParallelUnitTesting
{
[TestClass]
Public class ObjectWithIdentifierFixture
{
[TestMethod]
Public void TestPerThreadExecution ()
{
Parallel (
Delegate {ThreadInternalA ();},
Delegate {ThreadInternalB ();}
);
}
Void ThreadInternalA ()
{
WriteLine ("a1 ");
Thread. Sleep (2000 );
WriteLine ("a2 ");
}
Void ThreadInternalB ()
{
WriteLine ("b1 ");
Thread. Sleep (1000 );
WriteLine ("b2 ");
}
# Region Helper Methods
Static void WriteLine (string message)
{
Trace. WriteLine (string. Format ("thread {0 }:{ 1}", Thread. CurrentThread. ManagedThreadId, message ));
}
Static void Parallel (params ThreadStart [] actions)
{
List <Thread> threads = actions. Select (a => new Thread (a). ToList ();
Threads. ForEach (t => t. Start ());
Threads. ForEach (t => t. Join ());
}
# Endregion
}
}
The execution result is shown in the Output window as follows: (TestDriven. NET is used here)
------ Test started: Assembly: ParallelUnitTesting. dll ------
Thread 13: a1
Thread 14: b1
Thread 14: b2
Thread 13: a2
1 passed, 0 failed, 0 skipped, took 2.86 seconds (Ad hoc ).
Note: delegate. BeginInvoke is not used here because it may use a thread pool, so that multiple threads are not actually started.