How to read combobox from a thread other than the thread it was created on?

馋奶兔 提交于 2019-11-28 22:20:45

问题


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?


回答1:


You can do it like this:

this.Invoke((MethodInvoker)delegate()
    {
        text = combobox.Text;
    });



回答2:


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.




回答3:


Shortest way is:

string text;
this.Invoke(() => text = combobox.Text);



回答4:


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



来源:https://stackoverflow.com/questions/5516111/how-to-read-combobox-from-a-thread-other-than-the-thread-it-was-created-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!