C# - ThreadPool QueueUserWorkItem使用? [英] C# - ThreadPool QueueUserWorkItem Use?
问题描述
private static void doStuff(string parameter)
{
//做东西
}
//调用(a)
ThreadPool.QueueUserWorkItem(a => doStuff(hello world ));
// call(b)
ThreadPool.QueueUserWorkItem(delegate {doStuff(hello world);});
还有其他使用变体的 ThreadPool.QueueUserWorkItem
?
最佳将是另一个1-Line-Call。如果可以使用 Func<>
或 Action<>
。
编辑:得到(b)从答案和评论,我更喜欢它。
您的问题的答案取决于您如何设计应用程序。你把它放在一个共同的项目中吗?你不想开一个简单的操作。
但是,您可以为接收参数,1参数,2参数等的ThreadPool QueueUserItem创建一个通用调用。这是很好的,而不是发送一个简单的字符串,并且限制。
这样你如何在WaitCallback中插入参数QueueUserItem:
ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate(object state))
{YourMethod(Param1,Param2,Param3);}),null);
还有一些想法的链接: br>
http://msdn.microsoft.com/en-us/library/4yd16hza。 aspx
.NET中的Generic ThreadPool
http://thevalerios.net/matt/2008/06/threadpoolqueueuserworkitem-with - 多个参数/
C#中的delegate.BeginInvoke和使用ThreadPool线程之间的区别
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"); });
So are there other use variations of ThreadPool.QueueUserWorkItem
?
Best would be another 1-Line-Call. If possible with use of Func<>
or Action<>
.
EDIT: Got (b) from the answers and comments and I like it better already.
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.
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.
This how you impl a parameters QueueUserItem with WaitCallback:
ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate(object state)
{ YourMethod(Param1, Param2, Param3); }), null);
taken from C# Execute Method (with Parameters) with ThreadPool
And some links for ideas:
http://msdn.microsoft.com/en-us/library/4yd16hza.aspx
Generic ThreadPool in .NET
http://thevalerios.net/matt/2008/06/threadpoolqueueuserworkitem-with-multiple-arguments/
Difference between delegate.BeginInvoke and using ThreadPool threads in C#
这篇关于C# - ThreadPool QueueUserWorkItem使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!