Is it necessary to call CheckAccess () on the DIspatcher when executing the change UI method?

I have code that is sometimes called from the UI thread and sometimes from other threads.

    public void Notify(string message)
    {
        if (message == null)
        {
            throw new ArgumentNullException("message", string.Empty);
        }

        var actions = _invocationList.GetActions(message);

        if (actions != null)
        {
            Unity.Container.Resolve<Dispatcher>()
                .Invoke(new Action(() => actions.ForEach(action => action.DynamicInvoke())));
        }
    }

      

In the above example, should we add a condition with Dispatcher.CheckAccess () and just fire the action without a dispatcher in that case, or is it enough to just invoke the action using Invoke no matter which thread we are currently in? Why?

+3


source to share


1 answer


If you have a look at how the method is implemented Invoke(action)

, you can see what checkAccess()

is done automatically. So you don't need to do that either.

Here is the relevant portion of the source code from the class Dispatcher

:



// Fast-Path: if on the same thread, and invoking at Send priority,
// and the cancellation token is not already canceled, then just
// call the callback directly.
if(!cancellationToken.IsCancellationRequested && priority == DispatcherPriority.Send && CheckAccess())

      

You can see for yourself by translating the code starting here .

0


source







All Articles