WinRT vs. Silverlight - Part 4 - Dispatcher

See intro blogpost here.

In Silverlight and WPF you will often use the Dispatcher to return from a background thread to jump to the UI Thread. This is required when you need to update your UI, because you’re not allowed to touch the UI from anything but the UI Thread. The Dispatcher method has changed slightly in WinRT. It’s also now of type “CoreDispatcher”, instead of just “Dispatcher”.

#if !NETFX_CORE
  Dispatcher.BeginInvoke(
#else
  Dispatcher.Invoke(CoreDispatcherPriority.Normal, 
#endif
           (s, a) => { ... }
#if NETFX_CORE
      , this, null);
#endif
   );

Comments (6) -

  • Hello,

    Are you not confusing Invoke and InvokeAsync here ?

    ++
  • Jonathan: No in this case I'm using them synchronously. I'm not waiting for the method to complete firing on the other thread before continuing my execution as you would with InvokeAsync where you would be awaiting for the method to return. You should only use InvokeAsync if you want to execute some code back on your background thread when the UI thread execution has completed.
  • I Know but in your case you won't have the same
    Behavior in SL and WinRT  because BeginInvoke just do it in another Thread ... Smile
  • Ben
    Jonathan: BeginInvoke doesn't execute in another thread (will be useless), it does execute the code on the Dispatcher but asynchronously (understand later). But I agree with you BeginInvoke and Invoke is not exactly the same behavior.

    Morten: Imagine this (stupid) code
    DummyClass entity = null;
    #if !WINRT
      Dispatcher.BeginInvoke(
    #else
      Dispatcher.Invoke(CoreDispatcherPriority.Normal,
    #endif
               (s, a) => { entity = new DummyClass(); }
    #if WINRT
          , this, null);
    #endif
       );
    entity.Item1 = string.Empty;

    In Silverlight you're not assured that entity will not be null while in WinRT you are no?
  • With the async pattern you shouldn't have to often need to call the Dispather, isn't it?
  • Manuel: That really depends. The async pattern only applies to stuff that fires one event (for instance WebClient.DownloadingString), but it doesn't apply to other parts of the API that constantly fires events (ie sensors like compass, gps and gyro, various types of progress events, frame event etc). In those cases you will often still have events firing and need to update the UI thread with that information.

Pingbacks and trackbacks (3)+

Add comment