I write custom worker component and want it to fire it’s events on GUI thread. But I don’t want it to know about any existing windows. Also sometimes I have moments when there’s no window at all (transition between login and main window). So I can’t use Window.Dispatcher.BeginInvoke(). What are the other ways?
Share
Pass (or get using
Current) aSynchronizationContextto your worker. This is a lower level threading object that represent a particular context of execution (usually a thread), onto which you can post custom actions using thePostmethod. In case of a WPF application,SynchronizationContext.Postwill useDispatcher.BeginInvoke. It’s a good way to write background components that invoke events or send messages to a specific context without being tied to a particular implementation.Plus, it’s very easy to write a synchronous
SynchronizationContextthat doesn’t use threads at all to easily unit test your component without adding any asynchronous complexity.