BackgroundWorker multithread access to form

后端 未结 5 1594
刺人心
刺人心 2020-12-29 16:29

I am using 5 BackgroundWorker objects running at the same time for a certain purpose, and all of them have to change the same label. How do I do that?

How do I modif

5条回答
  •  猫巷女王i
    2020-12-29 16:50

    Use Control.Invoke with a delegate.

    In your background worker thread, instead of saying

    label4.Text = "Hello";
    

    say

    label4.Invoke(new Action(() =>
    {
      label4.Text = "Hello";
    }
    ));
    

    Everything inside the { } executes on the control's thread, so you avoid the exception.

    This allows you to do arbitrary changes to your user interface from a BackgroundWorker rather than just reporting progress.

提交回复
热议问题