可能重複:
Access return value from Thread.Start()'s delegate functionC#線程方法返回一個值?
public string sayHello(string name)
{
return "Hello ,"+ name;
}
我如何使用線程這種方法嗎?
ThreadStart方法只接受void方法。
我在等你的幫助。 謝謝。
可能重複:
Access return value from Thread.Start()'s delegate functionC#線程方法返回一個值?
public string sayHello(string name)
{
return "Hello ,"+ name;
}
我如何使用線程這種方法嗎?
ThreadStart方法只接受void方法。
我在等你的幫助。 謝謝。
ThreadStart
不僅期望無效的方法,它也希望他們不要拿任何參數!您可以將其包裝在一個lambda,一個匿名委託或一個命名的靜態函數中。
這裏是做這件事的一種方法:
string res = null;
Thread newThread = new Thread(() => {res = sayHello("world!");});
newThread.Start();
newThread.Join(1000);
Console.Writeline(res);
這裏是另一個語法:
Thread newThread = new Thread(delegate() {sayHello("world!");});
newThread.Start();
第三個語法(以命名函數)是最無聊:
// Define a "wrapper" function
static void WrapSayHello() {
sayHello("world!);
}
// Call it from some other place
Thread newThread = new Thread(WrapSayHello);
newThread.Start();
您應該爲此使用Task。
如果你可以使用線程的任何方法,嘗試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;
}
它一直對我有幫助。謝謝。 – 2012-01-14 04:35:16
我無法獲得返回值。如何使用返回值? – 2012-01-14 04:38:13
[ParameterizedThreadStart Delegate](http://msdn.microsoft.com/zh-cn/library/system.threading.parameterizedthreadstart.aspx) – 2012-01-14 04:41:54