C# 执行方法(带参数)与 ThreadPool [英] C# Execute Method (with Parameters) with ThreadPool

查看:20
本文介绍了C# 执行方法(带参数)与 ThreadPool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有以下代码段(此代码的想法可在此网站上找到),它将为方法Do_SomeWork()"生成新线程.这使我们能够多次异步运行该方法.

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.

代码是:

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

然而,我们希望使用 ThreadPool 而不是创建我们自己的新线程,这可能会损害性能.问题是我们如何修改上面的代码以使用 ThreadPool 记住方法Do_SomeWork"接受多个参数并且还有一个返回类型(即方法不是空的).

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).

另外,这是 C# 2.0.

Also, this is C# 2.0.

推荐答案

几乎相同的方式,但使用传递给 ThreadPool.QueueUserWorkItem 的 WaitCallback:

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

这篇关于C# 执行方法(带参数)与 ThreadPool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆