现在我正在使用下面的代码来添加排队的线程。我不喜欢这个。我的同事也不会,因为他们不太了解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
是否还有其他使用变体
最好的办法是再打一次单线电话。如果可能,请使用Func<>
或Action<>
。
编辑:从答案和评论中得到了(b),我已经更喜欢它了。
发布于 2013-07-02 15:49:48
您的问题的答案取决于您如何设计应用程序。你会把它放在一个普通的项目中吗?你不会想要一个简单的操作开销。
但是,您可以为接收参数、1个参数、2个参数等的ThreadPool QueueUserItem创建一个通用调用。这很好,而不是发送一个简单的字符串并受到限制。
下面是用WaitCallback实现参数QueueUserItem的方法:
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
Difference between delegate.BeginInvoke and using ThreadPool threads in C#
发布于 2013-07-02 15:48:13
我不完全确定您在寻找哪种语法,但是如果您不喜欢示例中未使用的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!"); });
但这有什么意义呢?它的可读性差得多!
发布于 2017-04-29 22:26:34
那这个呢?
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(MyWork, "text");
Console.ReadKey();
}
private static void MyWork(object argument)
{
Console.WriteLine("Argument: " + argument);
}
}
或者,如果你不想限制签名,并且有一种简单的方法将方法放在线程上,你可以像this.For方法那样做,这些方法可以返回值,也可以不返回值,并且有多达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<T>(this object @object, Action<T> 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");
}
}
https://stackoverflow.com/questions/17419961
复制相似问题