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

前端 未结 4 1995
眼角桃花
眼角桃花 2020-12-25 11:43

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

相关标签:
4条回答
  • 2020-12-25 12:20

    Shortest way is:

    string text;
    this.Invoke(() => text = combobox.Text);
    
    0 讨论(0)
  • 2020-12-25 12:29

    You can do it like this:

    this.Invoke((MethodInvoker)delegate()
        {
            text = combobox.Text;
        });
    
    0 讨论(0)
  • 2020-12-25 12:31

    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.

    0 讨论(0)
  • 2020-12-25 12:37

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

    0 讨论(0)
提交回复
热议问题