Search code examples
c#async-awaitwndproc

How can I call an asynchronous method from WndProc?


I have a program where I use custom message to call some methods from WndProc, like this:

protected override void WndProc(ref Message m)
{
    switch ((uint)m.Msg)
    {
        case WM_QUIT:
            Application.Exit();
            return;
        case WM_STARTOP:
            Context.TændNas();
            m.Result = new IntPtr(1);
            break;
    }
    base.WndProc(ref m);
}

Now I want to make the methods asynchronous. However, I can't add the async keyword to the WndProc override.

If I make Context.TændNasAsync an async method, how can I call it from WndProc?

Conclusion:

I go for @Hans Passant's suggestion, creating an async eventhandler. That way I can call the async method on the UI thread, while keeping it asynchron (awaitable).


Solution

  • This should work:

    Task.Run(()=>Context.TaendNas());
    

    or rather:

    Task.Run(async ()=> await Context.TaendNas());