开发者

Running a job in parallel with N concurrent threads

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 ?

[Te开发者_高级运维stMethod()]
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);
}


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.


Yes, I test some methods parallel with the TPL.

Here is some example code :

var parent = Task.Factory.StartNew(() =>
            {
                var tasksI = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < Constants.TaskCount; i++)
                        DoMethod1Parallel();

                });

                var tasksII = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < Constants.TaskCount; i++)
                        DoMethod2Parallel()

                });

                tasksI .Wait();
                tasksII.Wait();
            });

            parent.Wait();
            Assert.AreNotEqual(parent.IsFaulted, "Executing is faulted!");

I call Method1 and Method2 more than once and with the TPL parallel. So I can verify the capability of parallel execution!

Regards, patrick

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜