Oga*_*nlı 19 c# multithreading return void
public string sayHello(string name)
{
return "Hello ,"+ name;
}
Run Code Online (Sandbox Code Playgroud)
我如何在Thread中使用此方法?
ThreadStart方法只接受void方法.
我在等你的帮助.谢谢.
das*_*ght 38
不仅ThreadStart期望void方法,它还期望它们不接受任何参数!您可以将其包装在lambda,匿名委托或命名静态函数中.
这是一种方法:
string res = null;
Thread newThread = new Thread(() => {res = sayHello("world!");});
newThread.Start();
newThread.Join(1000);
Console.Writeline(res);
Run Code Online (Sandbox Code Playgroud)
这是另一种语法:
Thread newThread = new Thread(delegate() {sayHello("world!");});
newThread.Start();
Run Code Online (Sandbox Code Playgroud)
第三种语法(带有命名函数)是最无聊的:
// Define a "wrapper" function
static void WrapSayHello() {
sayHello("world!);
}
// Call it from some other place
Thread newThread = new Thread(WrapSayHello);
newThread.Start();
Run Code Online (Sandbox Code Playgroud)