从异步/等待方法返回列表

编程入门 行业动态 更新时间:2024-10-19 23:24:52
本文介绍了从异步/等待方法返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使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(),您的列表将被同步下载,您无需使用Task,async或await.

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()); }

更多推荐

从异步/等待方法返回列表

本文发布于:2023-11-08 20:27:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570375.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!