6

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)
svick
  • 236,525
  • 50
  • 385
  • 514
ilansch
  • 4,784
  • 7
  • 47
  • 96
  • 2
    Could you elaborate a little further what you want to accomplish? In particular: Where do you want to return a list of objects? In GetAnObject. Because then "public async Task> GetAnObject(string objectPath)" is perfectly valid. You just have to return a list of objects instead... – bigge Mar 12 '13 at 07:48

2 Answers2

23

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()
mariozski
  • 1,134
  • 1
  • 7
  • 20
2

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)
{
}
svick
  • 236,525
  • 50
  • 385
  • 514
TaraW
  • 225
  • 1
  • 9