Is it possible to reuse the same Task<T> created with Task.FromResult for instant returning methods (as it is completed already anyway)?
My reasoning behind the question is to reduce garbage produced by implementations of async interfaces that complete instantly (Task<bool> would be a great example for it, as it only has two possible values).
Base on this article about disposing of tasks, it should be possible, if .NET Core behaves the same (does it?).
Yes, and this is actually strongly recommended in cases where you have a small set of likely results that might be known synchronously (from cache, etc). Likewise, in the case of Task
(not Task<T>
), Task.CompletedTask
can be used.
Note that if most of your calls complete synchronously but you do not have a small domain of likely results, you might want to consider ValueTask<T>
, which is optimized for this case.
Everything here applies equally to both .NET and .NET Core.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With