异步方法是否有可能在C#中返回null?

问题描述 投票:-1回答:1

浏览一些旧代码,我注意到调用了async方法,然后检查了返回的任务是否为null

async Task<Something> DoSomeStuffAsync()
{
    //...
    return null; //not the actual return, but I guess it doesn't matter
}


var result = DoSomeStuffAsync(); //without await
if(result == null)
{
    //does this part makes any sense
}

根据我对async关键字的理解,这种情况将永远无法实现,因为async方法的结果将始终包裹在Task中,但只是检查一下,我是否遗漏了什么?

async方法是否将在C#中返回null

c# .net-core async-await task
1个回答
1
投票

标记为async的方法不可能返回null

但是,对于调用方,一个方法是否不是async,它只返回一个可等待的(一个Task ...或其他可等待的类型,超出了问题的范围),因此确实有可能返回null

即,呼叫者无法区分:

async Task Foo()
//...

和:

Task Foo()
//...

并且后一种方法可以完美地返回null

因此,空检查是完全有效的对于呼叫者

© www.soinside.com 2019 - 2024. All rights reserved.