Zéiksz
Zéiksz

Reputation: 696

Why MessageDialog does not work?

My goal is to have a messagedialog, that is in a portable library, so I can use it in Metro C#/XAML and Windows Phone as well.

I googled around and found this: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.popups.messagedialog , what would fit my needs.

After it's example I made this code:

public static async Task<string> Egyszerű(string Fejléc, string Szöveg, params string[] Gombfeliratok)
{
  string kérdésreAdottVálasz = null;

  MessageDialog kérdés = new MessageDialog(Szöveg, Fejléc);
  foreach (string válasz in Gombfeliratok)
  {
    kérdés.Commands.Add(new UICommand(válasz, new UICommandInvokedHandler(delegate { kérdésreAdottVálasz = válasz; })));
  }
  kérdés.DefaultCommandIndex = 0;
  kérdés.CancelCommandIndex = 1;
  await kérdés.ShowAsync();

  //esetleges utófeldolgozás helye itt
  //..

  return kérdésreAdottVálasz;
}

}

and put this into the portable library.

I call this from main program:

private void someEvent(object sender, ItemClickEventArgs e)
{
  if (Kérdés.Egyszerű("SURE?", "Are you sure, blablabla?", "YES", "NO").Result == "YES")
  {
    //stuff
  }
}

The message dialog appears, and I can answer as well, but right after that the program will freeze. The delegate does not run.

Can anyone please tell me, how to fix this or show a better (and I mean working) example to make such dialog?

Upvotes: 0

Views: 345

Answers (1)

Servy
Servy

Reputation: 203811

When you write: Kérdés.Egyszerű("SURE?", "Are you sure, blablabla?", "YES", "NO").Result you are blocking the UI thread until the asynchronous operation finishes, so that you can access its result.

Egyszerű is scheduling a continuation (everything after the await) to run in the UI thread, when it is available.

So your UI thread is waiting for Egyszerű to finish, and Egyszerű is waiting for the UI thread to be available before it can finish. Deadlock.

You need to not block the UI thread while waiting for the operation to finish. You need to "async all the way up" so that the UI stays responsive and is able to execute the continuations of the bottom most event.

private async void someEvent(object sender, ItemClickEventArgs e)
{
    if (await Kérdés.Egyszerű("SURE?", "Are you sure, blablabla?", "YES", "NO") 
        == "YES")
    {
        //stuff
    }
}

Upvotes: 1

Related Questions