C# Async Task Method Without Await or Return

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

I have an Interface I that is implemented in two places like:

interface I  {     Task DoSomething(); }

The interface has async Task DoSomething method API that is then implemented in class A like:

class A : I {....}  class B : I {....}

In class A, the implementation of DoSomething is like below and that is OK:

public async Task DoSomething() {     if (...)     {         await DoIt();     } }

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.

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.

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.

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

回答1:

public Task DoSomething() {     return Task.CompletedTask; }

No need for the async.

If you're using an older version of .NET, use this:

public Task DoSomething() {     return Task.FromResult(0); }

If you find you need to return a result but you still dont need to await anything, try;

public Task<Result> DoSomething() {     Task.FromResult(new Result()) }

or, if you really want to use async (not recommended);

public async Task<Result> DoSomething() {     return new Result(); }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!