WPF Dispatching, Invoking...

Infographics by vecteezy.com

found in PRISM platform (I checked ver. 4). We can publish there our events in global Container. But some times we won't use it or we can't. I created something similar to prism solution, so it's not quite my idea, but I think it can be helpful.

I created some structures:

- Dispatching class
- UIDispatcher class
- InvokeOptions enumeration


First of all, and a basic thing, is to get UI Dispatcher. UI Dispatcher is a default WPF application dispatcher, co we can get it from static field like below.



But before we can use it, we should check if Application.Current isn't null. It can be null in special cases, e.g. when we run Visual Studio Unit Tests.




Because sometimes we can get null instead of Dispatcher instance, I found iteresting solution in PRISM. We can create something similar to small bridge class, that will help to omit this issue. This class here will be called UIDispatcher.




UIDispatcher is a simple class that have BeginInvoke method used to invoke some delegate in UI Thread, using UI Dispatcher if it is accessible. We can also pass arguments to this method.

Because I wanted to create universal invoking solution I decided to create similar invoke-thread-options to this in PRISM. So I created InvokeOptions enumeration.



I ignored comments to clean code. PublisherThread option invoke method in the current thread, UIThread - in UI Thread, BackgroundThread - in background worker as Thread Pool Work Item (in my opinion better solution than background worker).

Finally We can see a target class:


What we can see here, there are two methods Invoke, used to invoke our methods or delegates in one of Thread options. I created two methods because I often use parameterless methods or delegates so the second was not needed. The second is helpful with others.

And how to use it, to have all clear.




All of code presented here can be download in one file in Downloads section below.

Hope this will be helpful.

Comments