asynchronous - C# - does Task.FromResult incur a heavy penalty? -
i'm bit new async coding c#, , have encountered few places methods have implement (either interface or part of inherited service, or suggested default convention) marked async , expect task<t> return.
but don't have async code run; don't have needs await operator.
so ad-hoc workaround return await task.fromresult({normal code}); these kinds of methods, this...
public async task<jsonresult> id() { // if user not authenticated, 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 solve compile time errors, wondering if there inherit problem doing this. if so, methods getting around things marked async cannot change?
rather creating task, adding continuation task literally noting wrap in identical task, return first task created.
since have nothing await, there no reason method marked async.
considering performance costs of fromresult pointless discussion. need create task based on result have, work needs done. considering how expensive is irrelevant have no alternative options. try create own fromresult method if think can write 1 that'll perform better microsoft's version.
that said, no, not particularly expensive of operation.
Comments
Post a Comment