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>
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
Cannot await System.Collections.Generic.List expression
I think I haven't fully understood the async/await methods. What I'm doing wrong?
This question is related to
c#
list
asynchronous
async-await
task
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());
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.
Instead of doing all these, one can simply use ".Result" to get the result from a particular task.
eg: List list = GetListAsync().Result;
Which as per the definition => Gets the result value of this Task < TResult >
you can use the following
private async Task<List<string>> GetItems()
{
return await Task.FromResult(new List<string>
{
"item1", "item2", "item3"
});
}
Source: Stackoverflow.com