C#: Running a job in parallel with N concurrent threads

Running a job in parallel with N concurrent threads

Problem:

Sometimes I need a test method to be executed simultaneously by N threads (like what happens in ASP.NET code).

Is there an easy way to do that with Task Library ?

[TestMethod()]

public void DoSomethingTest()

{

// Do something which has concurrency issues i.e. database, IO, …

DoSomething();

}

// Something like:

[TestMethod()]

public void DoSomethingTest()

{

int n = 1000; // run 1000 of DoSomething() simultaneously

Parallel.Invoke(() => DoSomething(), n);

}

Solution:

Yes, there is a Parallel.For :

[TestMethod()]

public void DoSomethingTest()

{

int n = 10; // changed to 10, see comment

Parallel.For(0, n, i => DoSomething());

// here all threads are completed

}

But note that the TPL will decide the amount of parallelism, much like the ASP.NET Threadpool…

You can add ParallelOptions to set the degeree of parallelism but I wouldn’t.

References:

http://stackoverflow.com/questions/5802257/running-a-job-in-parallel-with-n-concurrent-threads

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s