[英]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
- 它只能要求Task
或Task<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
指定为返回类型,并且您想要异步执行某些操作,那么您有两个选择:
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.