SharpGIS

#GIS from a .NET developer's perspective

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) -

  • Jonathan ANTOINE

    9/17/2011 3:07:17 PM |

    Hello,

    Are you not confusing Invoke and InvokeAsync here ?

    ++

  • Morten

    9/18/2011 10:02:36 AM |

    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.

  • Jonathan ANTOINE

    9/18/2011 10:47:06 AM |

    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

    9/19/2011 5:48:10 PM |

    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?

  • Manuel Riezebosch

    9/29/2011 12:56:49 AM |

    With the async pattern you shouldn't have to often need to call the Dispather, isn't it?

  • Morten

    9/30/2011 9:50:38 AM |

    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)+

Comments are closed