Question

private readonly CoreDispatcher dispatcher;

I am initializing above field in constructor to CoreWindow.GetForCurrentThread().Dispatcher; Then I wrapped a function around it:

public async Task OnUiThread(Action action)
{
    await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
}

and using this function to transfer calls to UIThread whneva required.It works fine.

Since I was doing this on every page of my application I decided to rathar maker a static class say

public static class ThreadManager
{
    private static readonly CoreDispatcher dispatcher;

    static ThreadManager()
    {
        dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
    }

    public static async Task OnUiThread(Action action)
    {
        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
    }
}

but now when I try to use this on my pages to transfer calls to UI thread, I get object null exception and dispatcher is shown null everywhere on other pages whereva I make the call to this static class. Why?

Was it helpful?

Solution

Well, you're initializing the CoreDispatcher based on whichever thread happens to initialize the class. Given that you really want it to be done for a specific dispatcher, this feels like it's a bad idea to me.

Given that you're using this from a page, can't you use the dispatcher for that page instead? I don't see why you need a dispatcher variable at all... you might consider writing an extension method for OnUiThread instead.

Also, you don't really need to use async/await here - or a lambda expression. You can just use:

public static Task OnUiThread(this CoreDispatcher dispatcher, Action action)
{
    return dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                               new DispatchedHandler(action))
                     .AsTask();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top