Ciel February 2016

C# - does Task.FromResult incur a heavy penalty?

I'm a bit new to async coding with C#, and have encountered a few places where methods I have to implement (either from an interface or part of an inherited service, or just suggested default convention) are marked async and expect a Task<T> return.

But I don't always have async code to run; I don't always have something that needs an await operator.

So my ad-hoc workaround is to just return await Task.FromResult({normal code}); to these kinds of methods, like this...

public async Task<JsonResult> Id() {
    // if the user is not authenticated, simply return false
    if (!User.Identity.IsAuthenticated || String.IsNullOrEmpty(User.Identity.Name))
        return await Task.FromResult(Json(false));
    return await Task.FromResult((Json(User?.FindFirst("users/id")?.Value ?? null)));
}

This does solve the compile time errors, but I was wondering if there is an inherit problem with doing this. If so, what are good methods for getting around things marked as async that I cannot change?

Answers


Servy February 2016

Rather than creating a Task, then adding a continuation to that task that does literally noting but wrap it in an identical Task, just return the first task that you created.

Since you have nothing to await, there is no reason for the method to be marked as async.

Considering the performance costs of FromResult is a pointless discussion. You need to create a task based on the result that you have, so that work needs to be done. Considering how expensive it is is irrelevant as you have no alternative options. You could try to create your own FromResult method if you think you can write one that'll perform better than Microsoft's version.

That said, no, it is not particularly expensive of an operation.

Post Status

Asked in February 2016
Viewed 1,262 times
Voted 10
Answered 1 times

Search




Leave an answer