-1

I run an awaited function in the constructor of my WPF application:

  Task.Run(async () =>
  {
      var r = await checkValidLicenseAsync(hardwareid);
      if (r == false)
        MessageBox.Show("no License.");
  }

The messagebox is not blocking my main window. I think this is because I run in a task? What is a workaround?

daniel
  • 34,281
  • 39
  • 104
  • 158

2 Answers2

0

What are you expecting from running this code as a task? It does not provide any advantage here. The possibly long running license validation is already being called with await making it non-UI blocking (unless its implementation is messed up).

To make the message box blocking, i.e. modal, simply write

  bool valid = await checkValidLicenseAsync(hardwareid); // non-blocking
  if (!valid) {
      MessageBox.Show("no License."); // blocking
  }

Assuming that this is the System.Windows.MessageBox and not its winforms pendant.

A possible approach is to use a factory method to return the object. Another one is to use an AsyncLazy<T> as described here by Stephen Cleary

See also: - Svick's answer to Can constructors be async?.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
-1

I don't think you can call an awaitable method into an constructor. Since constructor can't be added an async descriptor. You can call an delegate in an constructor. Just wrap your logic into a async delegate