1

I have the following async method:

public async Task<Result> Create(ModelStateDictionary modelState, TCreateViewModel postedModel)
{
    var result = new Result();
    if (! modelState.IsValid)
    {
        result.CopyErrorsFromModelState(modelState);
        return result;
    }

    // never reached if modelState is invalid
    var attemptCreateResult = await AttemptCreate(dataModel);
    result.MergeResult(attemptCreateResult);

    return result;
}

Say I changed it to the below. (I know it's kind of silly, but it's just to demonstrate.)

public async Task<Result> Create(ModelStateDictionary modelState, TCreateViewModel postedModel)
{
    var result = new Result();
    if (! modelState.IsValid)
    {
        result.CopyErrorsFromModelState(modelState);
    }

    return await Task.FromResult(result);
}

If ModelState is not valid, it would follow the exact same code path.

Yet on the first, I can return the result directly. And in the second I would be required to wrap my return result in Task.FromResult().

Can somebody explain to me why this is?


NOTE: I've really struggled to make this question clear, and not sure I've succeeded. I'd welcome any edits to clarify it. Thanks.

Martin Hansen Lennox
  • 2,837
  • 2
  • 23
  • 64
  • https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await?rq=1 – Nkosi Mar 24 '18 at 20:36
  • 2
    the second snippet is technically not async and can actually be removed. `return Task.FromResult(result);`. You are tryign to await an already completed Task in the second one. In the first one a state machine is created because of the proper use of async await. – Nkosi Mar 24 '18 at 20:38
  • Yeah, I know the second example is a bit dumb. But in the first example, if ModelState is not valid, the await operator contained within would never get hit. And I think that it would be the equivalent of the second. – Martin Hansen Lennox Mar 24 '18 at 20:41
  • 1
    no it wont. just because it does not reach the await does not make it the same as the second. – Nkosi Mar 24 '18 at 20:42
  • So the await (even if not hit) makes a difference in how the compiler runs the method? – Martin Hansen Lennox Mar 24 '18 at 20:42
  • 1
    Yes it does make a difference. – Nkosi Mar 24 '18 at 20:43
  • Ok, thanks. If you want to post as an answer I can mark it. – Martin Hansen Lennox Mar 24 '18 at 20:46
  • 1
    In both methods you can call `return result;` How do you conclude "in the second I would be required to wrap my return result in Task.FromResult()." ? The compiler automatically wraps the result into a task for you because the method is marked async. – Mike Zboray Mar 24 '18 at 21:20
  • It gave me a warning because the async method lacked await operators. – Martin Hansen Lennox Mar 25 '18 at 00:47

0 Answers0