-1

I am getting the compiler error

CS1061 'MAUserVM' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'MAUserVM' could be found (are you missing a using directive or an assembly reference?)

Async Method

public class MAUserVM
{
    public string AuthenticationStatus;

    public MAUser mAUser;

    public async Task<MAUserVM> GetMAUserAsync(string Email, string Password, IConfiguration configuration, IHttpContextAccessor accessor)
    {
        ...
    }
}

Calling method

private async Task<Boolean> AuthenticateUser(string email, string password)
{
    ...

    // exception happening here
    userVM = await userVM.GetMAUserAsync(email, password, _configuration, _accessor).Result;

    ...
}

What is causing this?

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
WinFXGuy
  • 1,527
  • 7
  • 26
  • 47

1 Answers1

7

The fix

//userVM = await userVM.GetMAUserAsync(email, password, _configuration, _accessor).Result;
userVM = await userVM.GetMAUserAsync(email, password, _configuration, _accessor);

The short story

You are calling Result on a Task which returns the T (aka MAUserVM), then trying to await it.


The long story

You can await any instance that exposes GetAwaiter (either as an instance method or extension method). A GetAwaiter needs to implement the INotifyCompletion interface (and optionally the ICriticalNotifyCompletion interface) and return a type that itself exposes several members. Task is one such object that implements the above (which is why you can await it)

The compiler error is telling you MAUserVM does not have the GetAwaiter method because you had already retrieved it (the result) from the Task using the Result method.

Gets the result value of this Task<TResult>.

Further more

In modern .Net, If you ever find your self calling Result, Wait or similar hackery, always think to yourself there is a better way, and that way is usually just call await. If you ignore this advice you will likely be blocking on an async method and find yourself with deadlocks, convoluted aggregate exceptions, or hard to debug issues.


Additional Resources

Stephen Cleary - Don't Block on Async Code

TheGeneral
  • 79,002
  • 9
  • 103
  • 141