C# Execute Method (with Parameters) with ThreadPool

偶尔善良 提交于 2019-11-29 07:15:27

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

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)

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