尝试理解ThreadPool方法QueueUserWorkItem的两种变体。
string bigS = "Big Stupid";
ThreadPool.QueueUserWorkItem( s =>
{
Console.WriteLine("Working on a thread from threadpool B");
Console.WriteLine("s = {0}", s.ToString());
}, bigS);
ThreadPool.QueueUserWorkItem(MethodA, bigS);MethodA的定义如下所示。
private static void MethodA(object o)
{
Console.WriteLine("o = {0}", o.ToString());
}这两种方式都很好。但是还有另一种QueueUserWorkItem的变体,它接受方法的委托,接受单个参数并返回空。所以methodA应该没问题。但是下面的代码抛出异常,因为我没有在MethodA中传递对象o。我不想在MethodA中为o检查null。如何将第二个案例中的bigS传递给MethodA
ThreadPool.QueueUserWorkItem(MethodA);另一种方法可能是这样的。但我想传递并访问o。我能做到这一点吗?
ThreadPool.QueueUserWorkItem( o =>
{
Console.WriteLine("Working on a thread from threadpool");
});发布于 2015-10-29 23:43:21
这在MSDN文档中不是很清楚,但是
ThreadPool.QueueUserWorkItem(callback);等同于
ThreadPool.QueueUserWorkItem(callback, null);如果在创建此API时存在可选参数,则很可能只有一种方法,如
public static bool QueueUserWorkItem(WaitCallback callBack, object state = null)但是有一件事documentation (备注部分)是明确的-如果你想让你的回调接收一些东西,你需要传递它,也就是使用带有state参数的重载。
发布于 2015-10-29 23:44:49
中的o
ThreadPool.QueueUserWorkItem( o =>
{
Console.WriteLine("Working on a thread from threadpool");
});将始终为空。它之所以出现在那里,是因为QueueUserWorkItem需要一个被定义为Action<object>的WaitCallback。我认为微软开发人员只是不想定义第二个WaitCallback代表。在Action和Func出现之前,ThreadPool就已经实现了。
你可以用你的lambda来捕获bigS
string bigS = "Big Stupid";
ThreadPool.QueueUserWorkItem( _ =>
{
Console.WriteLine("Working on a thread from threadpool B");
Console.WriteLine("s = {0}", bigS);
});或者,如果必须使用MethodA,则如下所示
string bigS = "Big Stupid";
ThreadPool.QueueUserWorkItem( _ =>
{
MethodA(bigS);
});https://stackoverflow.com/questions/33417976
复制相似问题