IDispatcherService

Jun 8, 2012 at 10:33 AM

Hi Geert,

could you please also introduce another function to the IDispatcherService?

(or change the current BeginInvoke)

The current BeginInvoke function does not fit very well into threading and

access to the UI because the "Action" is always called async from another thread

and that causes an error when accessing UI Elements.

public void BeginInvokeIfRequired(Action action)
{
       Argument.IsNotNull("action", action);
       Dispatcher dispatcher = DispatcherHelper.CurrentDispatcher;
       if (dispatcher != null && !dispatcher.CheckAccess())
      {
              dispatcher.BeginInvoke(action, null);
              return;
       }
       action(); 
}
Many Thanks!
Jun 9, 2012 at 1:31 PM

The current BeginInvoke function in the DispatcherService causes the following error when accessing UI Elements with it:

"The calling thread must be STA, because many UI components require this."

I want to delegate functions asynchronous to the UI thread with the DispatcherService

but it's not possible because Action.BeginInvoke executes async on a threadpool thread.

It would be very helpful if you could add the above function which executes an action

only async if not on the same thread.

DispatcherService.cs: (this is the current version)

public void BeginInvoke(Action action)
        {
            Argument.IsNotNull("action", action);

            var dispatcher = DispatcherHelper.CurrentDispatcher;
            if (dispatcher != null && !dispatcher.CheckAccess())
            {
#if NETFX_CORE
                dispatcher.InvokeAsync(CoreDispatcherPriority.Normal, (s, e) => action(), this, null);
#else
                dispatcher.BeginInvoke(action, null);
#endif
            }
            else
            {
#if SILVERLIGHT
                action.Invoke();   
#else
               // --------------------- this causes the error
                action.BeginInvoke(null, null);   // <<<--- should be also Invoke as above in the silverlight version
              // ----------------------
#endif
            }
        }

many thanks!

Jun 12, 2012 at 7:55 AM

I will change this.

Jun 12, 2012 at 2:10 PM

thanks a lot!