Home > Mobile >  How to call methods asynchronously from WPF HwndSource hook?
How to call methods asynchronously from WPF HwndSource hook?

Time:03-18

Per the instructions at https://stackoverflow.com/a/11378213/892770, I've registered a global hotkey for my WPF app like this:

this.helper = new WindowInteropHelper(this);
this.source = HwndSource.FromHwnd(this.helper.Handle);
this.source.AddHook(this.HwndHook);

I'd like to make async calls from the hotkey handler to allow me to avoid hanging the UI thread and update the window piecemeal, for example:

private async Task OnHotKeyPressed()
{
    this.MyText = "Loading...";
    this.MyText = await CallRestApi();
}

Unfortunately I can't figure out how to do this. The AddHook method doesn't have an overload for async methods, and if I wrap my handler in a .Result, or AsyncContext.Run(...) the UI doesn't get updated until the whole method's done. Any ideas? Thanks!

CodePudding user response:

The AddHook method doesn't have an overload for async methods ...

No, it hasn't, and there is nothing you can do about this, i.e. you cannot change the synchronous API.

But since the hook parameter represents an event handler that will receive all window messages, you can still implement the event handler asynchronously like you are already doing:

private async void OnHotKeyPressed() { ... }

As already mentioned, the general guideline is to avoid async methods that returns void except for event handlers that cannot return anything else. In other words, it's perfectly fine to use the async and await keywords in event handlers.

  • Related