mark_h
mark_h

Reputation: 5477

Why use Task.FromResult<T>(T result) from a method that contains awaits?

I came across the following method in a tutorial;

    private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
    {
        if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            return await Task.FromResult<ClaimsIdentity>(null);

        // get the user to verifty
        var userToVerify = await _userManager.FindByNameAsync(userName);

        if (userToVerify == null) return await Task.FromResult<ClaimsIdentity>(null);

        // check the credentials
        if (await _userManager.CheckPasswordAsync(userToVerify, password))
        {
            return await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userName, userToVerify.Id));
        }

        // Credentials are invalid, or account doesn't exist
        return await Task.FromResult<ClaimsIdentity>(null);
    }

The author always uses await Task.FromResult<ClaimsIdentity>(...) even when returning null. I'm no expert in the Task-await pattern and would have written the method something like this;

    private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
    {
        if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            return null;

        // get the user to verifty
        var userToVerify = await _userManager.FindByNameAsync(userName);

        if (userToVerify == null) return null;

        // check the credentials
        if (await _userManager.CheckPasswordAsync(userToVerify, password))
        {
            return _jwtFactory.GenerateClaimsIdentity(userName, userToVerify.Id);
        }

        // Credentials are invalid, or account doesn't exist
        return null;
    }

Both compile. What is the difference (if any) between these two methods? Is there anything to be gained by using await Task.FromResult<ClaimsIdentity>(null) in this manner?

Upvotes: 2

Views: 3420

Answers (1)

user6440521
user6440521

Reputation:

According to the best stackoverflow answer I've found about Task.FromResult: https://stackoverflow.com/a/19696462/6440521

The usage of Task.FromResult is appropriate only in the context of synchronous methods and mocking. So using it in an async method when you just want to return a result is redundant - gives you no additional benefits, also AsyncGuidance does not say anything about using Task.FromResult in an async method: https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md

So AFAIK using Task.FromResult in an async method is unnecessary, bloats your code and gives you no real benefits.

Upvotes: 3

Related Questions