Search code examples
wpfdispatcher

WPF Dispatcher Thread


I have a WPF application that at start up inits a named pipe server on a separate thread.
At some point in time, named pipe clients send info to this thread that in turn needs to update an Observable Collection in the ViewModel.
Attempting to do so directly results in an exception "cannot access collection of this time on a non dispatcher thread" ( I am paraphrasing the error a bit ).
At any rate how do I get the handler of the named pipe thread onto the UI thread. I don't seem to have a dispatcher object lying around that I can use to invoke a method. Am I supposed to cache on at start up into a static or singleton or some such.
The DispatcherSynchronizationContext looks interesting but not sure how to get one in my view and store in my View Model.


Solution

  • You are always able to access the Dispatcher of the Current Application instance by

    var dispatcher = Application.Current.Dispatcher;
    

    As soon as you've got this, you may execute actions on the UI thread by Invoke or BeginInvoke.