从异步/等待方法返回列表 [英] Return list from async/await method

查看:93
本文介绍了从异步/等待方法返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使Web服务请求异步.我在这里称呼它:

I want to make a webservice request asynchron. I call it here:

List<Item> list = GetListAsync();

这是我的函数的声明,该函数应返回一个列表:

Here is the declaration of my function, which should return a list:

private async Task<List<Item>> GetListAsync(){
    List<Item> list = await Task.Run(() => manager.GetList());
    return list;
}

如果我要编译,则会出现以下错误

If I want to compile I get the following error

Cannot implicitely convert type System.Threading.Tasks.Task<System.Collections.Generic.List<Item>> to System.Collections.Generic.List<Item>

据我所知,如果使用async修饰符,则结果将自动封装在Task中.我认为这不会发生,因为我使用了Task.Run.如果删除Task.Run(() =>部分,我将得到

As I know If I use the async modifier the result is automatically wrapped with Task. I think this doesn't happen because I use Task.Run. If I remove the Task.Run(() => part I get

无法等待System.Collections.Generic.List表达式

Cannot await System.Collections.Generic.List expression

我认为我还没有完全理解async/await方法.我在做什么错了?

I think I haven't fully understood the async/await methods. What I'm doing wrong?

推荐答案

您需要更正代码以等待列表下载:

You need to correct your code to wait for the list to be downloaded:

List<Item> list = await GetListAsync();

还要确保此代码所在的方法具有async修饰符.

Also, make sure that the method, where this code is located, has async modifier.

出现此错误的原因是GetListAsync方法返回的Task<T>不是完整的结果.由于您的列表是异步下载的(由于Task.Run()),您需要使用await关键字从任务中提取"值.

The reason why you get this error is that GetListAsync method returns a Task<T> which is not a completed result. As your list is downloaded asynchronously (because of Task.Run()) you need to "extract" the value from the task using the await keyword.

如果删除Task.Run(),您的列表将被同步下载,您无需使用Taskasyncawait.

If you remove Task.Run(), you list will be downloaded synchronously and you don't need to use Task, async or await.

另一个建议:如果您要做的只是将操作委托给另一个线程,则不需要在GetListAsync方法中等待,因此您可以将代码缩短为以下内容:

One more suggestion: you don't need to await in GetListAsync method if the only thing you do is just delegating the operation to a different thread, so you can shorten your code to the following:

private Task<List<Item>> GetListAsync(){
    return Task.Run(() => manager.GetList());
}

这篇关于从异步/等待方法返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆