C# thread method return a value? [duplicate]

断了今生、忘了曾经 提交于 2019-12-04 07:59:07

问题


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?

That ThreadStart method just accept void methods.

I'm waiting your helps. Thank you.


回答1:


Not only does ThreadStart expect 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.

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();



回答2:


You should be using a Task for that purpose.




回答3:


If you can use any method of threading, try 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;
}


来源:https://stackoverflow.com/questions/8860141/c-sharp-thread-method-return-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!