Zapnologica
Zapnologica

Reputation: 22556

How to override a function that returns a task

I have the following fucntion:

public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    return base.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);
}

I want to modify it to something like this:

public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    var result = base.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);

    //If status was successful do some thing here
    if(result =  success)
    {
       //update last logged in time.
    }

    //Lastly return the result
    return result;
}

Now I want to modify what the function does.

I want to execute the base task, and then use the result from it to do something in my overriding function?

How can I do this?

Upvotes: 4

Views: 3679

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You do so by adding the async keyword to the method, and awaiting the base operation:

public async override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    var result = await base.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);

    // Check result
    return result;
}

Because the provided base call returns a Task<T> which is awaitable, you can await it's asynchronous completion using async-await.

Note this means you would have to go "async all the way" and make sure the calls are properly awaited throughout the callstack.

More on async-await can be found here

Upvotes: 6

Related Questions