How to read combobox from a thread other than the

2019-02-02 03:23发布

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 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

Additional information: Cross-thread operation not valid: Control 'levelsComboBox' accessed from a thread other than the thread it was created on.

I have used .Invoke before but only to set properties, how can I use it to read combobox.Text? Because .Invoke returns void and I need a string. Or is there another way to do it without the Invoke?

4条回答
Ridiculous、
2楼-- · 2019-02-02 04:08

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).

查看更多
做自己的国王
3楼-- · 2019-02-02 04:15

You can do it like this:

this.Invoke((MethodInvoker)delegate()
    {
        text = combobox.Text;
    });
查看更多
等我变得足够好
4楼-- · 2019-02-02 04:16

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.

查看更多
迷人小祖宗
5楼-- · 2019-02-02 04:18

Shortest way is:

string text;
this.Invoke(() => text = combobox.Text);
查看更多
登录 后发表回答