Deb
Deb

Reputation: 991

Create Async Wrapper for a NonAsync Method

I am writting a middleware for Asp.Net Identity UserStore where the caller expects a Task and the Method to be called is NonAsynch.

Task IUserSecurityStampStore<T, string>.SetSecurityStampAsync(T user, string stamp)
{


    var res = Utility.SetSecurityStamp(user, stamp); // needs to be called as Async

    var identityUser = ToIdentityUser(res);

    SetApplicationUser(user, identityUser);

    return ??? ; // How do i get a task to return here ?

}

How do i return a Task out of res and stamp? Tried Task.FromResult but it says only one type argument is allowed.

Upvotes: 0

Views: 973

Answers (1)

Thomas
Thomas

Reputation: 29492

So your code could become something like that:

async Task IUserSecurityStampStore<T, string>.SetSecurityStampAsync(T user, string stamp)
{
    var res = await Task.Run(() => Utility.SetSecurityStamp(user, stamp));
    var identityUser = ToIdentityUser(res);
    SetApplicationUser(user, identityUser);
}

Or you can just use Task.FromResult to make your method awaitable :

async Task IUserSecurityStampStore<T, string>.SetSecurityStampAsync(T user, string stamp)
{
    var res = Utility.SetSecurityStamp(user, stamp);
    var identityUser = ToIdentityUser(res);
    SetApplicationUser(user, identityUser);

    await Task.FromResult(0);
}

Upvotes: 1

Related Questions