1

Relevant code is as follows:

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
    MessageDialog dialog = new MessageDialog("Wrong username or passwork. Please try again.");
    await dialog.ShowAsync();
    this.LoginButton.IsEnabled = true;
});

When I run this, E_ACCESSDENIED is thrown.

Is async-await here allowed?

Yuck
  • 49,664
  • 13
  • 105
  • 135
Isilmë O.
  • 1,668
  • 3
  • 23
  • 35

1 Answers1

5

Dispatcher.RunAsync is not designed to take an async delegate. It is designed to itself return a Task so that it can be awaited. The method that you give it should be non-async method.

The actual signature of the delegate it accepts is public delegate void DispatchedHandler()

Because the delegate is void returning RunAsync will think that it's finished as soon as it awaits for the first time, rather than when it's actually done. This means that whatever code is awaiting this method is continuing on well before it should.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • It's a little misleading I think.:( The compiler allows doing async while at runtime it fails. Well, I'm using Dispatcher because it throws E_ACCESSDENIED exception when the KeyDown event handler of a TextBox, which calls await dialog.ShowAsync(), is invoked. Isn't it on the same thread as the main UI? Why is the action denied? – Isilmë O. Jul 01 '13 at 14:47
  • @IsilmëOrphousV This is why you need to be wary of `async void` methods. The compiler has to allow it, even though it's usually not appropriate. As for the error, all I can say is that this code isn't doing what it should be doing, but there isn't enough of your code shown to know what, specifically, is going wrong from here. Perhaps `RunAsync`, since it think's it's done, won't keep it's current context alive, or perhaps it doesn't set the current sync context at all, I'm not sure. In any case, this doesn't appear to be the proper use of `RunAsync`. – Servy Jul 01 '13 at 14:50
  • See this question about awaiting the actual work being done: http://stackoverflow.com/questions/19133660/runasync-how-do-i-await-the-completion-of-work-on-the-ui-thread – Luke Puplett Apr 01 '14 at 18:00