如何声明和等待异步委托?

How to declare and await an async delegate?

出于某种原因,尽管这个问题在我的谷歌搜索中出现了很多次,但我似乎找不到真正的答案。也许我只是错误地使用了代表,我不确定。如果这是一个 X-Y 问题,我很高兴有其他处理方法。

假设我有这个:

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);
    }
}

应该没问题(除了愚蠢的拼写错误)。

现在想象一下我的常规同步 DoSyncProcessing 函数突然变成了异步的,就像在这个神奇的非功能代码中一样:

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);
    }
}

我该如何处理?正确的做法是什么?

async 修饰符影响方法实现,而不是签名。所以改变这个:

public async delegate Task OnSomethingHappened(EventInfo eventInfo);

为此:

public delegate Task OnSomethingHappened(EventInfo eventInfo);

您的代码将起作用。