Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Execute Method (with Parameters) with ThreadPool

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.

like image 400
washtik Avatar asked Aug 02 '26 03:08

washtik


1 Answers

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();
like image 188
Remus Rusanu Avatar answered Aug 04 '26 17:08

Remus Rusanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!