Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UI dispatcher in class library

I'd like to design a class library and plan to use mutli-threading (i.e. BackgroundWorker). I will have to watch out for the thread context, from which updates are made for fields, if I plan to bind them to the GUI of the library consuming frontend. It's not a good idea to pass the reference of the GUI dispatcher to the library, as I read. But how can I get access to the dispatcher of the application that will use the library? Is this possible?

I tried Application.Current.Dispatcher and added a reference to WindowBase (as I didn't have the possibility to add System.Windows), but still can't resolve the dispatcher object.

like image 597
rdoubleui Avatar asked May 30 '11 20:05

rdoubleui


3 Answers

The Application class is defined in PresentationFramework.dll. You need to reference that in order to be able to access the dispatcher through Application.Current.Dispatcher.

like image 166
John Leidegren Avatar answered Oct 01 '22 06:10

John Leidegren


I had same issue ie not being able to resolve Application.Current.Dispatcher and ended up passing the client gui dispatcher down to the library which just holds a Dispatcher ref (reference WindowsBase + using System.Windows.Threading).
I prefer this option that having my non GUI lib have to carry a ref to PresentationFramework.dll (which doesn't seem natural).
I guess its 6 of one, half a dozen of the other...

like image 25
Ricibob Avatar answered Oct 01 '22 05:10

Ricibob


If you make sure (such as with static members of a class) that you have a handy reference to the UI Dispatcher, you can do this:

public static void Run( Action a ) {
    if ( !_uiDispatcher.CheckAccess() ) {
        _uiDispatcher.BeginInvoke( a );
    }
    else {
        a();
    }
}

One or two MVVM frameworks I've looked at do stuff like this.

If you don't want to pass this Dispatcher reference down to the library, IoC containers are an option. You could also put this in a Common.dll for classes and interfaces that both the exe and class libraries need to reference. The exe can set up the correct reference, and the class library can call the Run() method.

like image 35
Joel B Fant Avatar answered Oct 01 '22 05:10

Joel B Fant