小编典典

异步等待返回任务

c#

有人可以解释一下同步方法意味着什么吗?如果我尝试将方法更改为asyncVS,则会对此有所抱怨。

这有效:

public Task MethodName()
{
     return Task.FromResult<object>(null);
}

这不起作用:

public async Task MethodName()
{
     return Task.FromResult<object>(null);
}

所以基本上我想知道这到底意味着什么: Task.FromResult<object>(null);


阅读 532

收藏
2020-05-19

共1个答案

小编典典

async方法与普通方法不同。从async方法返回的所有内容都包装在Task

如果不返回任何值(无效),则将其Task换行;如果返回int,则将其换行Task<int>,依此类推。

如果您的异步方法需要返回int你标记方法的返回类型Task<int>,你会返回纯int不是Task<int>。编译器将转换intTask<int>你。

private async Task<int> MethodName()
{
    await SomethingAsync();
    return 42;//Note we return int not Task<int> and that compiles
}

同样,返回时,Task<object>方法的返回类型应为Task<Task<object>>

public async Task<Task<object>> MethodName()
{
     return Task.FromResult<object>(null);//This will compile
}

由于您的方法正在返回Task,因此不应返回任何值。否则它将无法编译。

public async Task MethodName()
{
     return;//This should work but return is redundant and also method is useless.
}

请记住,没有await声明的异步方法不是async

2020-05-19