Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...