sillyrobot
sillyrobot

Reputation: 163

Why can't I cast from Action to DispatchedHandler?

G'day Folks,

I feel like I'm can't see something basic.

Action is defined as public delegate void Action().

DispatchedHandler is defined as public delegate void DispatchedHandler().

Yet the following code generates at the RunASync line: Error CS1503 Argument 2: cannot convert from 'System.Action' to 'Windows.UI.Core.DispatchedHandler'.

public static async Task DispatchToUI(Action action, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal )
{
    if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
    {
        action();
    }
    else
    {
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( priority, action );
    }
}

Adding an explicit conversion thus:

await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( priority, (DispatchedHandler)action ); 

fails with Error CS0030 Cannot convert type 'System.Action' to 'Windows.UI.Core.DispatchedHandler'.

So one version of public delegate void() can't convert to a different version of public delegate void()?

Upvotes: 0

Views: 230

Answers (1)

kaffekopp
kaffekopp

Reputation: 2619

You cannot convert a delegate like that, check this SO question.

You can, however, create a new delegate from the existing one:

public static async Task DispatchToUI(Action action, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
{
    if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
    {
        action();
    }
    else
    {
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(priority, new DispatchedHandler(action));
    }
}

Upvotes: 2

Related Questions