实施需要在同步码任务返回类型的接口 [英] Implementing an interface that requires a Task return type in synchronous code

查看:105
本文介绍了实施需要在同步码任务返回类型的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实施返回的接口方法的任务< T> 与同步代码,你可以使用 Task.FromResult< T>(结果) 。当结果就是工作有比使用类似 Task.FromResult℃的更好的选择;对象>(NULL);

When implementing an interface method that returns a Task<T> with synchronous code you can use the Task.FromResult<T>(result). When the result is just Task is there a better option than using something like Task.FromResult<object>(null);?

推荐答案

在一般的答案是否定的。

In general the answer is no.

一个工作是这可能是一个lambda或者委托一个动作的包装。所以如果你想你的方法返回一个工作对象,那么你需要实例化一个工作实例或一些别的地方找回。

A Task is a 'wrap' of an action which could be a lambda or delegate. So if you want your method return a Task object then you need instantiate a Task instance or retrieve it from some where else.

要实例化工作实例有两种方式 - 无论是使用构造函数或一些工厂方法。正如前面提到的,任务包装动作,所以你需要调用构造函数

To instantiate a Task instance you have 2 approaches - either use constructor or some factory methods. As mentioned, Tasks wraps an action, so you need provide an action in calling the constructor

static Task GetTask() 
{
    return new Task(() => { });
}



或者,如果你希望你的工作有返回值,你可以做如下

Or if you want your Task have a return value, you could do as below

static Task GetTask() 
{
    return new Task<object>(() => null);
}



另一种方法是使用一个工厂方法创建这样一个任务。无论 Task.Factory 任务< T> .FromResult 是工厂方法,但没有两者有什么更好的选择。比你指定

The other approach is to use a factory method for creating such a Task. Both Task.Factory and Task<T>.FromResult are the factory methods, but none of both has any better option than you specified.

所以,再创建一个新的实例,你确实需要调用其中可能有一些必需的参数构造函数;或者使用一些提供的工厂方法。如果你发现他们都不方便,我相信一个定制的工厂/助手是您的解决方案。

So again, for creating a new instance you do need to call the constructor which may have some required arguments; or you use some provided factory methods. If you found none of them is convenient, I believe a customized factory/helper is your solution.

顺便说一句,基于C#的类型推理,如果返回类型为具体类型,如整数,你可以省略这是很简单早已类型做你的代码如下:

By the way, based on C# type inferring, if you return type is a concrete type such as integer, you could do your code as below by omitting the type which is simple enough already:

static Task GetTask() 
{
    return Task.FromResult(123);
}

你的例子是返回,所以类型不能由此推断你需要在你的代码中指定它(对象)。

As you example is to return null, so the type can not be inferred thus you need specify it (object) in you code.

这篇关于实施需要在同步码任务返回类型的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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