Simple Method for starting multi-thread parallel processing in unit test

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.