简体   繁体   中英

Use Task.FromResult for creating async action

Please consider this action method:

[HttpPost]
public async Task RemoveUserFromGroups(string connectionId, List<string> groupNames, string pusherAddress)
{
    var onlineUser = OnlineUser.Instance;
    await OnlineBusiness.RemoveUserFromGroups(onlineUser.Id, onlineUser.CustomerId, onlineUser.IsTrader, connectionId, groupNames, pusherAddress);
}

and this method:

public static Task<bool> RemoveUserFromGroups(int userId, int customerId, bool isTrader, string connectionId, List<string> groupNames, string pusherAddress)
{
    return Task.FromResult(PusherBusiness.RemoveUserFromGroups(userId, customerId, isTrader, connectionId, groupNames, pusherAddress));
}

The PusherBusiness class in a third party library that in the class call a web service. I want to change my controller to async mode.is this correct to use Task.FromResult and return Task and then await on it? Is this async?

No. This isn't asynchronous at all.

This will run synchronously, create a task, await that completed task (which completes synchronously) and move on using the same thread.

For this to be asynchronous you need some actually asynchronous operation in there. For example if RemoveUserFromGroups calls a web service it should do so asynchronously and offer RemoveUserFromGroupsAsync or at least Begin / EndRemoveUserFromGroups .

As long is doesn't offer that overload there's not much you can do to actually have an asynchronous operation.

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