Why can't UI components be accessed from a backgroundworker?

前端 未结 3 748
星月不相逢
星月不相逢 2021-01-21 18:20

Threads all share resources. That\'s the whole problem around multi-threaded operations.

MSDN says:

You must be careful not to manipulate any user

3条回答
  •  迷失自我
    2021-01-21 19:03

    If you're handler is an instance method in your UI class, you should have access to the members of that class.

    it's that my app won't even compile if I try to access the UI components from the DOWork event.

    This will only happen if your DoWork handler is static or in a different class than the UI components. In that case, you may not have access to them, as they are not visible to you.


    Edit:

    BackgroundWorker is intended to do "work" that is unrelated to your User Interface. You cannot change User Interface elements on any thread other than the UI thread, as user interface elements tend to have thread affinity. This actually has nothing to do with BackgroundWorker, but rather threading and user interface elements.

    BW is intended to work around this by giving you progress and completion events that are automatically marshalled back onto the UI thread for you, allowing you to change UI elements there. However, you can always do this directly yourself via Control.Invoke in Windows Forms or Dispatcher.Invoke in WPF.

    As to how this works - It depends on what framework you're using. For example, in Windows Forms, every Control (which is the base class of all of the UI elements) has a Handle, and the Handle is internally a native window handle. This handle is used to check the window's Thread ID against the current thread ID. This allows the check to be made without storing extra variables.

提交回复
热议问题