现在我正在使用以下代码添加排队线程.我不喜欢它.我的同事也不会,因为他们不太了解 C#.当然,我想要的只是将要在新线程中执行的方法排队.
Just right now I'm using following code to add queued threads. I don't like it. And my colleagues won't either because they don't know C# very well. All I want is of course to queue a method to be executed in a new thread.
private static void doStuff(string parameter)
{
// does stuff
}
// call (a)
ThreadPool.QueueUserWorkItem(a => doStuff("hello world"));
// call (b)
ThreadPool.QueueUserWorkItem(delegate { doStuff("hello world"); });
那么 ThreadPool.QueueUserWorkItem
还有其他使用变体吗?
So are there other use variations of ThreadPool.QueueUserWorkItem
?
最好是另一个 1-Line-Call.如果可能,请使用 Func<>
或 Action<>
.<小时>从答案和评论中得到 (b),我已经更喜欢它了.
Best would be another 1-Line-Call. If possible with use of Func<>
or Action<>
.
您的问题的答案取决于您如何设计应用程序.你把它放在一个共同的项目中吗?你不想开销一个简单的操作.
The answer for your question depends on how you design the application. Do you put it inside a common project ? you dont want to overhead a simple operations.
但是,您可以为接收参数、1 个参数、2 个参数等的 ThreadPool QueueUserItem 创建一个通用调用.这很好,而不是发送一个简单的字符串并受到限制.
But, You could create a generic call for ThreadPool QueueUserItem that receive params, 1 param, 2 param, etc.. This is good instead of sending a simple string and be restricted.
这就是你如何使用 WaitCallback 实现参数 QueueUserItem:
This how you impl a parameters QueueUserItem with WaitCallback:
ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate(object state)
{ YourMethod(Param1, Param2, Param3); }), null);
取自 C# Execute Method (with Parameters) with ThreadPool一个>
还有一些想法的链接:
http://msdn.microsoft.com/en-us/library/4yd16hza.aspx
.NET 中的通用线程池
delegate.BeginInvoke 和在 C# 中使用 ThreadPool 线程
And some links for ideas:
http://msdn.microsoft.com/en-us/library/4yd16hza.aspx
Generic ThreadPool in .NET
Difference between delegate.BeginInvoke and using ThreadPool threads in C#
这篇关于C# - ThreadPool QueueUserWorkItem 使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!