且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是Task.FromResult℃的替代; T>()为重新present操作返回void任务

更新时间:2022-04-12 04:01:52

任务< T> 扩展工作 - 所以这是相当常见,只使用 Task.FromResult<对象> ,并提供一个空的结果。例如:

Task<T> extends Task - so it's reasonably common to just use Task.FromResult<object> and provide an empty result. For example:

Task ret = Task.FromResult<object>(null);

(或者使用值类型 - 它确实没有多大关系。)

(Or use a value type - it really doesn't matter much.)

当然,作为任务是不可改变的,你可以创建这样的单一实例并返回它每一次你想返回的已完成的任务。 (我相信这是异步/的await基础设施做什么,其实 - 或beta版,至少没有...)

Of course, as tasks are immutable you could create a singleton instance of this and return it every time you want to return a completed task. (I believe that's what the async/await infrastructure does, in fact - or at least did in beta releases...)

由于阿萨德指出,你可以使用 Task.CompletedTask ,但只有当你的目标.NET 4.6。 (实际上,目前尚不清楚其是否支持是在.NET 4.5与否 - 文档显示的.NET Framework 4.6和4.5的版本号,但接着说支持:4.6...)

As Asad noted, you can use Task.CompletedTask, but only if you're targeting .NET 4.6. (Actually, it's not clear whether it's supporting in .NET 4.5 or not - the documentation shows ".NET Framework 4.6 and 4.5" as the version number, but then says "Supported in: 4.6"...)