Execute a delegate in the ui thread (using message pump)

后端 未结 5 1658
抹茶落季
抹茶落季 2020-12-19 16:18

I have a background thread that handles communication with an external service. Each time the background thread receives a message I\'d like to pass it to the UI thread for

5条回答
  •  星月不相逢
    2020-12-19 16:46

    There are a few techniques.

    1. Control.Invoke() (et al)

      I've found this winforms technique consistently easy to use, but be aware that there are some subtle rules you need to get right. I've tried to capture a general, working implementation that properly handles the rules in a code segment I've posted elsewhere on stackoverflow.

    2. SynchronizationContext

      I haven't needed to use this technique much, so I can't really say anything meaningful about it. You should know that it exists, however. I believe that it's an effective way to ensure something gets called in a particular thread's context, even if that thread is not the ui thread.

    3. DispatcherObject.Dispatcher

      If you're working with WPF, the WPF controls will generally derive from DispatcherObject to supply the Dispatcher object. This is a more feature-rich synchronization technique than the Control.Invoke(), but also more complex. Be sure to read the docs carefully.

提交回复
热议问题