C# 使用带参数的方法创建新线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14854878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating new thread with method with parameter
提问by Lio Lou
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------------
---------错误------------
Error: CS1502 - line 92 (164) - The best overloaded method match for '
System.Threading.Thread.Thread(System.Threading.ThreadStart)
' has some invalid argumentsError: CS1503 - line 92 (164) - Argument '1': cannot convert from 'method group' to '
System.Threading.ThreadStart
'
错误:CS1502 - 第 92 行 (164) - “ ”的最佳重载方法匹配
System.Threading.Thread.Thread(System.Threading.ThreadStart)
有一些无效参数错误:CS1503 - 第 92 行 (164) - 参数“1”:无法从“方法组”转换为“
System.Threading.ThreadStart
”
回答by gzaxx
Change your thread initialization to:
将您的线程初始化更改为:
var t = new Thread(new ParameterizedThreadStart(myMethod));
t.Start(myGrid);
And also the method to:
还有以下方法:
public void myMethod(object myGrid)
{
var grid = (UltraGrid)myGrid;
}
回答by ken2k
public void myMethod(object myGrid)
{
var typedParam = (UltraGrid)myGrid;
//...
}
Thread t = new Thread(new ParameterizedThreadStart(myMethod));
t.Start(myGrid);
回答by Igoy
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.
将参数传递给方法的一种更方便的方法是使用 lambda 表达式或匿名方法,这是因为您可以传递具有所需参数数量的方法。ParameterizedThreadStart 仅限于只有一个参数的方法。
Thread t = new Thread(()=>myMethod(myGrid));
t.Start();
public void myMethod(UltraGrid myGrid)
{
}
if you had a method like
如果你有一个像
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
http://www.albahari.com/threading/#_Passing_Data_to_a_Thread
Thats a great book to read!
这是一本值得阅读的好书!