Return list from async/await method
In addition to @takemyoxygen's answer the convention of having a function name that ends in Async
is that this function is truly asynchronous. I.e. it does not start a new thread and it doesn't simply call Task.Run
. If that is all the code that is in your function, it will be better to remove it completely and simply have:
List<Item> list = await Task.Run(() => manager.GetList());
You need to correct your code to wait for the list to be downloaded:
List<Item> list = await GetListAsync();
Also, make sure that the method, where this code is located, has async
modifier.
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.
If you remove Task.Run()
, you list will be downloaded synchronously and you don't need to use Task
, async
or await
.
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());
}
you can use the following
private async Task<List<string>> GetItems()
{
return await Task.FromResult(new List<string>
{
"item1", "item2", "item3"
});
}
Works for me:
List<Item> list = Task.Run(() => manager.GetList()).Result;
in this way it is not necessary to mark the method with async in the call.