问题描述
我有一个接口I,它在两个地方实现:
I have an Interface I that is implemented in two places like:
interface I
{
Task DoSomething();
}
该接口具有异步Task DoSomething方法API,然后在类A中实现该API,例如:
The interface has async Task DoSomething method API that is then implemented in class A like:
class A : I {....}
class B : I {....}
在A类中,DoSomething的实现如下所示,没关系:
In class A, the implementation of DoSomething is like below and that is OK:
public async Task DoSomething()
{
if (...)
{
await DoIt();
}
}
但是,在类B中,DoSomething()的实现不应执行任何操作. 因此,其实现如下所示:
However, in class B, the implementation of DoSomething() should not do anything. So, its implementation looks like this:
public async Task DoSomething()
{
// nothing
}
这可以编译,但是我不确定该方法有多正确,除了该方法无用的事实外,还可以执行类似的操作.
This compiles but I am not sure how correct it is do do something like this beside the fact that the method is useless.
但是在这种情况下无用"是可以的,因为仅由于实现接口I的类B要求实现它,就可以实现它.
But being "useless" in this case is ok in this case since it is implemented just because it is required by class B implementing the interface I.
我想知道这是否是实现返回异步Task但没有等待或返回的方法的正确方法吗?我知道此方法将简单地不执行任何操作并同步执行,因为没有等待调用的请求.
I wonder if this is a correct way to implement a method that returns async Task but has no await or return? I know that this method will simple do nothing and execute synchronously as there is no call to await.
更新:在SO上已经问过类似的问题,在问这个问题之前,我已经检查了所有这些问题.没有人在问我在问什么
UPDATE: Similar questions have been asked here on SO and I have checked all of them before asking this one. None is asking what I am asking though
推荐答案
public Task DoSomething()
{
return Task.CompletedTask;
}
不需要async
.
如果您使用的是.NET的旧版本,请使用以下命令:
If you're using an older version of .NET, use this:
public Task DoSomething()
{
return Task.FromResult(0);
}
如果发现需要返回结果,但仍然不需要await
任何内容,请尝试;
If you find you need to return a result but you still dont need to await
anything, try;
public Task<Result> DoSomething()
{
return Task.FromResult(new Result())
}
或者,如果您真的想使用异步(不推荐);
or, if you really want to use async (not recommended);
public async Task<Result> DoSomething()
{
return new Result();
}
这篇关于没有等待或返回的C#异步任务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!