BackgroundWorker - Cross-thread operation not valid

前端 未结 7 1111
南方客
南方客 2020-12-14 19:16

I have a winform application (one form), on this form there is a RichTextBox. In the constructor of this form I create an instance of the class MyClass. In the

7条回答
  •  情话喂你
    2020-12-14 19:49

    Using BackgroundWorker doesn't exempt you of the normal threading rules - such as that only the UI thread can access UI components.

    If you want to update the UI from a BackgroundWorker other than using the progress/completion events (which are raised on the UI thread) you need to use Control.Invoke / Control.BeginInvoke just as you would in other situations. For example:

    if (....)
    {
        Action action = () => richtextBox.Text.Add("MyText");
        richtextBox.Invoke(action); // Or use BeginInvoke
    }
    

提交回复
热议问题