I am trying to read a combobox.Text from a thread other than the thread it was created on but I am getting the error:
An unhandled exception of type
Shortest way is:
string text;
this.Invoke(() => text = combobox.Text);
You can do it like this:
this.Invoke((MethodInvoker)delegate()
{
text = combobox.Text;
});
You can still use Invoke
and read it to a local variable.
Something like this:
string text;
this.Invoke(new MethodInvoker(delegate() { text = combobox.Text; }));
Since Invoke
is synchronous you have the guarantee that text
variable will contain the value of the combo box text after it returns.
The easiest solution is to use the BackgroundWorker class to execute work on another thread, while still being able to update the UI (e.g. when reporting progress or when the task has completed).