C#5.0异步等待返回一个列表 [英] C# 5.0 async await return a list
问题描述
我学习异步/在等待着,碰到了一个情况,我需要调用异步方法
应返回的对象或相同的对象的列表。结果
这是贯彻落实正确的方式?
从AManager.cs
公共异步任务初始化(字符串objectPath)
{
AnObject someObject =等待BClass.GetAnObject(objectPath);
}
和这是被调用方法
B类:
公共异步任务< AnObject> GetAnObject(字符串objectPath)
{
AnObject someObj中=新AnObject();
返回someObj中;
}
如果我想返回对象的名单,会发生什么?我应该创建一个包含列表的包装?并返回包装?结果
因为这是不适用的:
公共异步任务<名单,LT; AnObject>> GetAnObject(字符串objectPath)
我不知道你想完成的任务&LT什么;列表< AnObject>>
是不适用,但这里是高于
公共类AnObject()
{
SomeProperty {搞定;组;}
一些方法();
}公共类theCollectionofAnObject:IList的< AnObject> ()
{
私人列表< AnObject> _contents =新的List< AnObject取代; //实现IList接口的其余部分}//你的异步方法
公共任务< theCollectionofAnObject> GetAnObjects(参数)
{
}
I'm learning about async/await, and ran into a situation where I need to call an async method
that should return an object or list of same object.
Is this the right way to implement ?
from AManager.cs
public async Task Initialize(string objectPath)
{
AnObject someObject = await BClass.GetAnObject(objectPath);
}
and this is the called method
Class B:
public async Task<AnObject> GetAnObject(string objectPath)
{
AnObject someObj = new AnObject();
return someObj;
}
What happens if I want to return a list of object ? I should create a wrapper that contains a list ? and return that wrapper ?
Because this is not applicable:
public async Task<List<AnObject>> GetAnObject(string objectPath)
I am not sure what you are trying accomplish that the Task<List<AnObject>>
is not applicable, but here is another example of returning a List of the AnObject in your example above
public class AnObject()
{
SomeProperty {get; set;}
Some Method();
}
public class theCollectionofAnObject : IList<AnObject> ()
{
private List<AnObject> _contents = new List<AnObject>;
//Implement the rest of IList interface
}
//Your async method
public Task<theCollectionofAnObject> GetAnObjects(parameter)
{
}
这篇关于C#5.0异步等待返回一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!