System.InvalidOperationException: 'A method was called at an unexpected time when calling LaunchUriAsync inside ToastNotification UWP

Viewed 576

I'm trying to open the browser with a specific URL using the method LaunchUriAsync when the user clicks a Toast notification.

The problem is that the application throws System.InvalidOperationException: 'A method was called at an unexpected time.

This only happens inside the Activated event handler of the ToastNotification.

If I execute this method outside the Activated event handler of the ToastNotification everything works fine.

Here is the code:

private async void OnActivatedEventHandler<TSender, TResult>(TSender sender, TResult args)
{
  Uri uri = new Uri("...");
  bool success = await Windows.System.Launcher.LaunchUriAsync(uri);
}

Can someone explain me why this happens ?

It's welcome any other approach to achieve something similar.

1 Answers

The error message said that the method is called at an unexpected time. From the document of Launcher.LaunchUriAsync Method, the remarks mentions that-'Unless you are calling this API from a Windows desktop application, this API must be called from within an ASTA thread (also known as the UI thread).' You need to call this method in the UI thread.

Related