简体   繁体   中英

Returning a generic task from a method

I am trying to implement the following method, in the public IUserStore interface, as I am using custom authentication:

public Task<User> FindByIdAsync(string userId)
{
    var user = UserRetriever.GetUser(userId);
    return ???;
}

UserRetriever works fine, and gets me my User object, but how do I return it?

If I try this:

return await user;

I get told that my user object 'is not awaitable'. Is there an interface I can implement on User to make it awaitable?

Alternatively is there an awaitable container I can put user into, to return it from this method?

You can use FromResult :

return Task.FromResult(user);

Note this only exists in .Net 4.5 and any user of your FindByIdAsync method will expect the fetch to occur asynchronously, which your current implementation does not do.

You may be able to create a task to do the retrieval instead:

return Task.Run(() => UserRetriever.GetUser(userId));

although this still has the problem of blocking.

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