C# thread method return a value? [duplicate] C# thread method return a value? [duplicate] multithreading multithreading

C# thread method return a value? [duplicate]


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" functionstatic void WrapSayHello() {    sayHello("world!);}// Call it from some other placeThread newThread = new Thread(WrapSayHello);newThread.Start();


You should be using a Task for that purpose.


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;}