Ɖiamond ǤeezeƦ
Ɖiamond ǤeezeƦ

Reputation: 3331

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 theasync...await` syntax. E.g.

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 'await' operator can only be used within an async method

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?

Upvotes: 2

Views: 267

Answers (2)

pomber
pomber

Reputation: 23980

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

Upvotes: 3

Peter pete
Peter pete

Reputation: 712

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

Upvotes: 1

Related Questions