使用 ThreadPool 执行 C# 方法(带参数)
我们有以下代码段(此代码的想法可以在本网站上找到),它将为方法“Do_SomeWork()”生成新线程。这使我们能够异步多次运行该方法。
代码是:
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”需要多个参数并且还有一个返回类型(即方法不是 void)。
另外,这是 C# 2.0。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 C# 2.0,您可以
在回调中调用 then,将 object[] 强制转换回正确的参数和类型。关于返回类型,如果使用ThreadPool我认为你无法获得返回值,回调必须有一个签名
With C# 2.0, you call
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
几乎相同的方式,但使用传递给 ThreadPool.QueueUserWorkItem 的 WaitCallback:
Pretty much the same way, but use a WaitCallback passed to ThreadPool.QueueUserWorkItem: