What is the point of .NET 4.6's Task.CompletedTask?

偶尔善良 提交于 2019-12-10 12:38:20

问题


This blog post mentions the new Task APIs, including a new Task.CompletedTask property introduced in .NET 4.6.

Why was this added? How is this better than, say, Task.FromResult(whatever)?


回答1:


Task.FromResult(whatever) works for Task<TResult>, but until 4.6 there was nothing for the nongeneric task. You could use FromResult with a dummy value and implicitly cast it to Task, but that somewhat obfuscates the intent (you're not really returning any asynchronous value) and allocates objects underneath (whereas CompletedTask can be cached and shared between all callers).

It's not uncommon to see custom static completed tasks in current (4.5.2 and older) codebases, so in my opinion it makes sense to incorporate it to the framework itself.



来源:https://stackoverflow.com/questions/30493036/what-is-the-point-of-net-4-6s-task-completedtask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!