什么是Task.FromResult℃的替代; T>()为重新present操作返回void任务 [英] What is an alternative for Task.FromResult<T>() for tasks that represent operations returning void

查看:291
本文介绍了什么是Task.FromResult℃的替代; T>()为重新present操作返回void任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是返回没有一个泛型类型参数任务的最佳方式?换句话说,稀土$ P $任务psents不返回任何东西,或返回一个操作无效

What is the best way to return a task that doesn't have a generic type parameter? In other words a task that represents an operation that doesn't return anything or returns void?

在换句话说,我要寻找以下选择:

In other words, I am looking for alternatives for the following:

T value = default(T);
return Task.FromResult<T>(value); // and

var tcs = new TaskCompletionSource<T>();
tcs.SetResult(value);
return tcs.Task;

但对于重新那些不应该返回任何present操作任务。

But for tasks that represent operations that are not supposed to return anything.

推荐答案

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

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

这篇关于什么是Task.FromResult℃的替代; T&GT;()为重新present操作返回void任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆