I’ve got a program that executes a method through a Thread.Start. The method has a return value that I’d like to get access to. Is there a way to do this? Here’s a sampling…
var someValue = "";
Thread t = new Thread(delegate() { someValue = someObj.methodCall(); });
t.Start();
while (t.isAlive) Thread.Sleep(1000);
// Check the value of someValue
So once the while loop ends, the someValue should be set – but because it’s executed in another thread it doesn’t get set. Is there a simple way to get access to it?
When the caller and the threaded method share a variable, you already have access to it – once the thread has completed, you just check
someValue.Of course, you have to know when the threaded method is complete for this to be useful. At the bottom, there are two ways to do this:
Send a callback into the threaded method that it can execute when it’s finished. You can pass your callback method
someValue. You can use this technique if you don’t care when the callback executes.Use a
WaitHandleof some kind (orThread.Join). These tell you when a resource is ready or an event has completed. This technique is useful if you want to start a thread, do something else, then wait until the thread completes before proceeding. (In other words, it’s useful if you want to sync back up with the thread, just not right away.)