views:

317

answers:

2

We have the following piece of code (idea for this code was found on this website) which will spawn new threads for the method "Do_SomeWork()". This enables us to run the method multiple times asynchronously.

The code is:

    var numThreads = 20;
    var toProcess = numThreads;

    var resetEvent = new ManualResetEvent(false);

    for (var i = 0; i < numThreads; i++)
    {
        new Thread(delegate()
        {
            Do_SomeWork(Parameter1, Parameter2, Parameter3);
            if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set();
        }).Start();
    }

    resetEvent.WaitOne();

However we would like to make use of ThreadPool rather than create our own new threads which can be detrimental to performance. The question is how can we modify the above code to make use of ThreadPool keeping in mind that the method "Do_SomeWork" takes multiple parameters and also has a return type (i.e. method is not void).

Also, this is C# 2.0.

+1  A: 

With C# 2.0, you call

ThreadPool.QueueUserWorkItem(callback, new object[] { parm1, parm2, etc });

Then inside the callback you cast the object[] back into the correct parameters and types. Regarding the return type, if using the ThreadPool I don't think you will be able to get the return value, the callback has to have a signature of

void Callback (object parm)

Otávio Décio
+1  A: 

Pretty much the same way, but use a WaitCallback passed to ThreadPool.QueueUserWorkItem:

var numThreads = 20;
var toProcess = numThreads;

var resetEvent = new ManualResetEvent(false);

for (var i = 0; i < numThreads; i++)
{
    ThreadPool.QueueUserWorkItem (
        new WaitCallback(delegate(object state) {
        Do_SomeWork(Parameter1, Parameter2, Parameter3);
        if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set();
    }), null);
}

resetEvent.WaitOne();
Remus Rusanu