C#线程方法返回一个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8860141/
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
C# thread method return a value?
提问by Ogan Tabanl?
Possible Duplicate:
Access return value from Thread.Start()'s delegate function
public string sayHello(string name)
{
return "Hello ,"+ name;
}
How can i use this method in Thread?
如何在 Thread 中使用此方法?
That ThreadStart method just accept void methods.
该 ThreadStart 方法只接受 void 方法。
I'm waiting your helps. Thank you.
我在等你的帮助。谢谢你。
采纳答案by dasblinkenlight
Not only does ThreadStartexpect void methods, it also expect them not to take any arguments! You can wrap it in a lambda, an anonymous delegate, or a named static function.
不仅ThreadStart期望 void 方法,还期望它们不接受任何参数!您可以将其包装在 lambda、匿名委托或命名静态函数中。
Here is one way of doing it:
这是一种方法:
string res = null;
Thread newThread = new Thread(() => {res = sayHello("world!");});
newThread.Start();
newThread.Join(1000);
Console.Writeline(res);
Here is another syntax:
这是另一种语法:
Thread newThread = new Thread(delegate() {sayHello("world!");});
newThread.Start();
The third syntax (with a named function) is the most boring:
第三种语法(带有命名函数)是最无聊的:
// Define a "wrapper" function
static void WrapSayHello() {
sayHello("world!);
}
// Call it from some other place
Thread newThread = new Thread(WrapSayHello);
newThread.Start();
回答by ispiro
If you can use any method of threading, try BackgroundWorker:
如果您可以使用任何线程方法,请尝试BackgroundWorker:
BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
bw.DoWork += bw_DoWork;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
bw.RunWorkerAsync("MyName");
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Text = (string)e.Result;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
string name = (string)e.Argument;
e.Result = "Hello ," + name;
}

