C# – ThreadPool QueueUserWorkItem使用?

就在我现在使用以下代码添加排队的线程。 我不喜欢它。 而且我的同事也不会因为他们不太了解C#。 我想要的当然是将一个方法排队在一个新线程中执行。

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还有其他用途吗?

最好的是另一个1-Line-Call。 如果可能,使用FuncAction


编辑:得到(b)答案和评论,我已经更喜欢它了。

您的问题的答案取决于您如何设计应用程序。 你把它放在一个共同的项目中吗? 你不想开销一个简单的操作。

但是,你可以为ThreadPool QueueUserItem创建一个接收params,1 param,2 param等的generics调用。这很好,而不是发送一个简单的字符串并受到限制。

这是你如何使用WaitCallback推送参数QueueUserItem:

 ThreadPool.QueueUserWorkItem( new WaitCallback(delegate(object state) { YourMethod(Param1, Param2, Param3); }), null); 

使用ThreadPool从C#Execute方法(带参数)中获取

还有一些想法的链接:
http://msdn.microsoft.com/en-us/library/4yd16hza.aspx
.NET中的通用ThreadPool
委托.BeginInvoke和在C#中使用ThreadPool线程之间的区别

我不完全确定你正在寻找什么样的语法,但如果你不喜欢你的例子中未使用的a ,为什么不使用Task呢?

 Task.Run(() => doStuff("hello world")); 

它看起来并没有好多少,但至少它没有未使用的标识符。

注意: Task.Run()是.Net 4.5或更高版本。 如果你使用.Net 4,你必须这样做:

 Task.Factory.StartNew(() => doStuff("hello world")); 

这并不短。

以上两者都使用线程池。

如果你真的必须避免使用lambda,你可以使用匿名委托(@nowhewhomustnotbenamed已经提到过):

 Task.Run(delegate { doStuff("Hello, World!"); }); 

但那有什么意义呢? 它的可读性低得多!

那这个呢?

 class Program { static void Main(string[] args) { ThreadPool.QueueUserWorkItem(MyWork, "text"); Console.ReadKey(); } private static void MyWork(object argument) { Console.WriteLine("Argument: " + argument); } } 

或者,如果您不想成为签名限制并且有一种简单的方法将方法放在线程上,您可以像这样执行。对于执行和不返回值并且最多包含6个参数的方法,需要您定义如果我没有弄错的话会超载12次。 它需要更多的工作,但使用起来更简单。

 class Program { static void Main(string[] args) { var myClass = new MyClass(); myClass.DoWork(); Console.ReadKey(); } } public static class ObjectThreadExtension { public static void OnThread(this object @object, Action action) { ThreadPool.QueueUserWorkItem(state => { action(); }); } public static void OnThread(this object @object, Action action, T argument) { ThreadPool.QueueUserWorkItem(state => { action(argument); }); } } public class MyClass { private void MyMethod() { Console.WriteLine("I could have been put on a thread if you like."); } private void MySecondMethod(string argument) { Console.WriteLine(argument); } public void DoWork() { this.OnThread(MyMethod); this.OnThread(MySecondMethod, "My argument"); } }