I've this little method which is supposed to be thread safe. Everything works till i want it to have return value instead of void. How do i get the return value when BeginInvoke is called?
public static string readControlText(Control varControl) {
if (varControl.InvokeRequired) {
varControl.BeginInvoke(new MethodInvoker(() => readControlText(varControl)));
} else {
string varText = varControl.Text;
return varText;
}
}
Edit: I guess having BeginInvoke is not nessecary in this case as i need value from GUI before the thread can continue. So using Invoke is good as well. Just no clue how to use it in following example to return value.
private delegate string ControlTextRead(Control varControl);
public static string readControlText(Control varControl) {
if (varControl.InvokeRequired) {
varControl.Invoke(new ControlTextRead(readControlText), new object[] {varControl});
} else {
string varText = varControl.Text;
return varText;
}
}
But not sure how to get value using that code either ;)
EndInvoke
may be used to get a return value from aBeginInvoke
call. For example:You have to Invoke() so you can wait for the function to return and obtain its return value. You'll also need another delegate type. This ought to work:
//simple & elegant but it is needed to wait for another thread to execute delegate; however if you cannot proceed without the results...
Is something like this what you wanted?
If you want a return value from you method, you shouldn't be using async version of the method, you should use
.Invoke(...)
. Which is synchronous, that is it will execute your delegate, and won't return until it's complete. In your example as it is now, BeginInvoke will send the request to execute your delegate, and return right away. So there is nothing to return.