简体   繁体   中英

Making interface implementations asynchronous

I am implementing System.Web.UI.IPostBackEventHandler on one of my classes and in the body of my implementation of void RaisePostBackEvent(string eventArgument) I am calling a method using the async...await` syntax. Eg

public void RaisePostBackEvent(string eventArgument)
{
    if (eventArgument.Equals("deq1"))
    {
        Result result = await SaveDataAsync();
        OnSaved();
    }
}

However, it produces the error:

CS4033 - The 'await' operator can only be used within an async method

CS4033-“等待”运算符只能在异步方法中使用

The question: Making interface implementations async describes an almost identical problem to mine, with the key difference being that the interface implemented by the OP was under his control, and the accepted answer was to change void DoSomething() on the interface to Task DoSomething() . However, I cannot change the IPostBackEventHandler as it is part of the .NET Framework.

Any suggestions on how to solve this in a safe way?

You can add the async modifier even if it is not defined in the interface.
Just take into account that RaisePostBackEvent must return void, so it will work as a "fire and forget" call. If that is not a problem just add the async modifier to the signature.

public async void RaisePostBackEvent(string eventArgument)
{
    if (eventArgument.Equals("deq1"))
    {
        Result result = await SaveDataAsync();
        OnSaved();
    }
}

If your method implementation is NOT async, then you cannot "await" inside it. You can make your method implementation async void even if the interface you're implementing doesn't have async. You cannot make your method implementation async Task, as that changes the return value which is bad.

The outcome of making your method implementation async void is that the caller will not wait for the method to complete before returning. try:

public async void RaisePostBackEvent(string eventArgument)
{
    if (eventArgument.Equals("deq1"))
    {
        Result result = await SaveDataAsync();
        OnSaved();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM