Currently I'm aware of the following Dispatcher
objects.
If you have a text view, you can use IWpfTextView.VisualElement.Dispatcher
.
If your class is constructed by MEF (marked with [Export]
and not directly constructed from your own code), then you can use the fact that the MEF part resolution algorithm and construction occurs on the UI thread, allowing the use of Dispatcher.CurrentDispatcher
. For example:
[Export(typeof(ISomeInterface))]
public class MyClass : ISomeInterface {
private readonly Dispatcher _dispatcher;
public MyClass() {
_dispatcher = Dispatcher.CurrentDispatcher.
}
}
You can use Application.Current.Dispatcher
from any code.
What, if any, is the recommended practice for obtaining a Dispatcher
?
Do not take a dependency on MEF composing on UI thread. If it works for you right now, you're just getting lucky. Also MEF is delayed in nature and full of Lazy, so if you happen to realize it on a background thread, the entire subgraph will get realized on background.
I would use #1 or #3 (doesn't matter which, there is only one UI thread dispatcher, doesn't matter how you get to it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With