Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing Task<T> in .NET core/.NET Standard

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?).

like image 466
Fionn Avatar asked Jun 05 '17 11:06

Fionn


1 Answers

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.

like image 136
Marc Gravell Avatar answered Oct 21 '22 06:10

Marc Gravell