Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# thread method return a value? [duplicate]

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.

like image 346
Ogan Tabanlı Avatar asked Jan 14 '12 04:01

Ogan Tabanlı


1 Answers

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();
like image 143
Sergey Kalinichenko Avatar answered Sep 29 '22 15:09

Sergey Kalinichenko