使用带有参数的方法创建新线程 [英] Creating new thread with method with parameter
问题描述
我正在尝试创建新线程并传递带有参数的方法,但出错了.
I am trying to create new thread and pass a method with parameter,but errors out.
Thread t = new Thread(myMethod);
t.Start(myGrid);
public void myMethod(UltraGrid myGrid)
{
}
---------错误------------
---------errors------------
错误:CS1502-92行(164)-最佳重载方法匹配'
System.Threading.Thread.Thread(System.Threading.ThreadStart)
'具有一些无效的参数
错误:CS1503-第92行(164)-参数"1":无法从方法组"到" System.Threading.ThreadStart
"
Error: CS1503 - line 92 (164) - Argument '1': cannot convert from
'method group' to 'System.Threading.ThreadStart
'
推荐答案
将参数传递给方法的一种更方便的方法是使用lambda表达式或匿名方法,这是因为可以传递具有所需参数数量的方法.ParameterizedThreadStart仅限于只有一个参数的方法.
A more convenient way to pass parameters to method is using lambda expressions or anonymous methods, why because you can pass the method with the number of parameters it needs. ParameterizedThreadStart is limited to methods with only ONE parameter.
Thread t = new Thread(()=>myMethod(myGrid));
t.Start();
public void myMethod(UltraGrid myGrid)
{
}
如果您有类似
public void myMethod(UltraGrid myGrid, string s)
{
}
Thread t = new Thread(()=>myMethod(myGrid, "abc"));
t.Start();
http://www.albahari.com/threading/#_Passing_Data_to_a_Thread
那是一本很棒的书!
这篇关于使用带有参数的方法创建新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!