Home > Back-end >  How to declare and await an async delegate?
How to declare and await an async delegate?

Time:09-17

For some reason, despite this question coming up a lot in my googling, I can't seem to find an actual answer. Maybe I'm just using delegates wrong, I'm not sure. I'm happy for alternative ways of handling this if it's an X-Y problem.

Say I have this:

public class SomeLibrary
{
    public delegate void OnSomethingHappened(EventInfo eventInfo);
    public OnSomethingHappened onSomethingHappened;
    
    public void SomeMethod()
    {
        // ...
        
        // Something happened here, so we'd better trigger the event
        onSomethingHappened?.Invoke(eventInfo);
        
        // ...
    }
}

public class MyCode
{
    public void SomeInitialisationMethod()
    {
        SomeLibrary someLibrary = new SomeLibrary();
        someLibrary.onSomethingHappened  = SomeEventHandler;
    }
    
    private void SomeEventHandler(EventInfo eventInfo)
    {
        DoSyncProcessing(eventInfo);
    }
}

That should all be fine (barring silly typos).

Now imagine my regular synchronous DoSyncProcessing function suddenly has to become asyncronous, like in this magic non-functional code:

public class SomeLibrary
{
    public async delegate Task OnSomethingHappened(EventInfo eventInfo); // <<< IDK what I'm doing here!
    public OnSomethingHappened onSomethingHappened;
    
    public void SomeMethod()
    {
        // ...
        
        // Something happened here, so we'd better trigger the event
        await onSomethingHappened?.Invoke(eventInfo);                            // <<< IDK what I'm doing here either!
        
        // ...
    }
}

public class MyCode
{
    public void SomeInitialisationMethod()
    {
        SomeLibrary someLibrary = new SomeLibrary();
        someLibrary.onSomethingHappened  = SomeEventHandler;
    }
    
    private async Task SomeEventHandler(EventInfo eventInfo)
    {
        await DoAsyncProcessing(eventInfo);
    }
}

How can I handle that? What's the correct way to do this?

CodePudding user response:

The async modifier affects the method implementation, not the signature. So change this:

public async delegate Task OnSomethingHappened(EventInfo eventInfo);

To this:

public delegate Task OnSomethingHappened(EventInfo eventInfo);

and your code will work.

  • Related