简体   繁体   English

C#的接口方法中什么时候使用Task?

[英]When to use Task in Interface Methods in C#?

There are interface methods that you obviously know that will be async , implementations that will read from the disk for example, you can easily decide to use Task .您显然知道某些接口方法将是async ,例如将从磁盘读取的实现,您可以轻松决定使用Task There are also interface methods that might use async , you can make them return Task too.还有一些接口方法可能使用async ,你也可以让它们返回Task

I can't help but see Task as an implementation detail that I'm hesitant to put Task on my interfaces when I'm not sure if the implementation will be async / will use async methods.我不禁将Task视为实现细节,当我不确定实现是否是async /将使用async方法时,我犹豫是否将Task放在我的接口上。 If I decide to not use Task , the implementation methods can't be async when needed.如果我决定不使用Task ,则实现方法在需要时不能是async的。

Although it feels weird to adjust the contract based on the requirement of the implementation, this is what I will do.虽然根据实现的需求来调整合约感觉很奇怪,但这是我会做的。 Is this the correct way?这是正确的方法吗?

Is this the correct way?这是正确的方法吗?

Yes.是的。 Just use Task if you know there will sometimes be opportunity to be asynchronous.如果您知道有时会有机会异步,请使用Task

That still leaves you the opportunity to not, because the interface cannot require the use of async - it can only require the return type of Task or Task<T> .这仍然让您有机会不这样做,因为接口不能要求使用async - 它只能要求TaskTask<T>的返回类型。

If you end up not needing to do anything asynchronously, you can use Task.FromResult() to return a completed Task with a value.如果您最终不需要异步执行任何操作,则可以使用Task.FromResult()来返回已完成的带有值的Task For example:例如:

protected override Task<int> SomeMethod() {
    return Task.FromResult(1);
}

Or Task.CompletedTask if there is no return value.或者Task.CompletedTask如果没有返回值。

Otherwise, if you don't specify Task as the return type, and you want to do something asynchronously, you're left with two options:否则,如果您没有将Task指定为返回类型,并且您想要异步执行某些操作,那么您有两个选择:

  1. Use synchronous methods in your implementation,在您的实现中使用同步方法,
  2. If no synchronous methods are available for what you want to do (which is increasingly common), then you either have to:如果没有同步方法可用于您想做的事情(这越来越普遍),那么您要么必须:
    • Block synchronously on the asynchronous methods, or在异步方法上同步阻塞,或
    • Use async void (if the method returns void ), which can cause other complications.使用async void (如果方法返回void ),这可能会导致其他并发症。

All of those are worse options than returning a completed Task in cases where you don't need to run asynchronously.在不需要异步运行的情况下,所有这些都是比返回已完成Task更糟糕的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM