C# Async Task Method Without Await or Return

主宰稳场 提交于 2019-12-05 03:03:14
sellotape
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()
{
    return Task.FromResult(new Result())
}

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

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

I see that most people prefer to leave out the async and use Task.ComletedTask instead. But even if await is not used, there is still a big difference in exception handling

Consider the following example

static async Task Main(string[] args)
{

    Task task = test(); // Will throw exception here
    await task;

    Task taskAsync = testWithAsync();
    await taskAsync; // Will throw exception here
}

static Task test()
{
    throw new Exception();
    return Task.CompletedTask; //Unreachable, but left in for the example
}

static async Task testWithAsync()
{
    throw new Exception();
}

Using

test().ContinueWith(...); or Task.WhenAll(test())

may result in unexpected behaviour.

Therefore, I prefer async instead of Task.CompletedTask or Task.FromResult.

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