C# 5.0 async await return a list

别来无恙 提交于 2019-12-03 15:49:10
TaraW

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)
{
}

To be able to run method as async you need to have await inside. If you won't have it it'll be run as synchronous method. That's probably why it did not work for you. To achieve this you can do something like this:

public async Task<List<string>> GetList()
{
    return await Task.Run(() => new List<string>() {"a", "b"});
}

And then to run it:

var list = await GetList()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!