C# Execute Method (with Parameters) with ThreadPool

妖精的绣舞 提交于 2019-11-28 00:52:39

问题


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:


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();



回答2:


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)



来源:https://stackoverflow.com/questions/2671634/c-sharp-execute-method-with-parameters-with-threadpool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!