Tip of the day : Using the Dispatcher

Maybe this is a well known problem, but I was finding that using the dispatcher from background threads was working, but using it when I was already on the foreground thread works sometimes and sometimes not (e.g., the invalidated objects never got updated on the screen).

Here’s my solution:

    public void SetPageTitle(string message)
    {
        UXExtensions.DoThreadSafeAction(this, () =>
        {
            this.titleText.TextContent = message;
            this.titleText.Invalidate();
        });
    }

Where DoThreadSafeAction looks like this:

using System;
using GHIElectronics.TinyCLR.UI;

namespace PervasiveDigital.Galaxy.UX
{
    public static class UXExtensions
    {
        public static void DoThreadSafeAction(UIElement uiElem, Action action)
        {
            if (uiElem.Dispatcher.CheckAccess())
            {
                action();
            }
            else
            {
                Application.Current.Dispatcher.Invoke(TimeSpan.FromMilliseconds(1), _ =>
                {
                    action();
                    return null;
                }, null);
            }
        }
    }
}

Other comments on this problem and my solution are warmly welcomed. Seems to me that this sort of self-invoke ought to be safe to do without this sort of shenanigans.

1 Like