How do I cast an Task<IEnumerable<IMapLocationItem>>
to an IEnumerable<IMapLocationItem>
?
Here is my code that gets a Task<IEnumerable<IMapLocationItem>>
:
public async Task<IEnumerable<IMapLocationItem>> GetAllMapLocationItemsFromUserName(string userName)
{
IEnumerable<IMapLocationItem> mapLocationImageGalleries = await db.mapLocationImageGalleries.Where(m => m.userName.Equals(userName)).ToListAsync();
IEnumerable<IMapLocationItem> mapLocationVideoGalleries = await db.mapLocationVideoGalleries.Where(m => m.userName.Equals(userName)).ToListAsync();
IEnumerable<IMapLocationItem> mapLocationItemsCombined = mapLocationImageGalleries.Concat(mapLocationVideoGalleries);
return mapLocationItemsCombined;
}
I can use the keyword .Result
, but I have read somewhere that this prevents the async
task from being asynchronous, and this method takes a very long time to finish when using the Result keyword.
How is the best way to cast a Task<IEnumerable<IMapLocationItem>>
to an IEnumerable<IMapLocationItem>
?
Thanks in advance
From the MSDN website http://msdn.microsoft.com/en-us/library/hh191443.aspx
// Signature specifies Task<TResult>
async Task<int> TaskOfTResult_MethodAsync()
{
int hours;
// . . .
// Return statement specifies an integer result.
return hours;
}
// Calls to TaskOfTResult_MethodAsync
Task<int> returnedTaskTResult = TaskOfTResult_MethodAsync();
int intResult = await returnedTaskTResult;
// or, in a single statement
int intResult = await TaskOfTResult_MethodAsync();
You cannot cast a task to the result. That defeats the purpose of async. What the code above does is calls the function asynchronously, then later in the code requests the result by calling "await". This will wait for the asnyc function to finish (will block the code until that is done) until the result is ready.
The issue is that you cannot predict when something will be done when it is running asynchronously, so instead we tell the Task when we are finally ready to wait for the result. It could be done right away or in 5 minutes. Await will wait for as long as it is necessary for the function to finish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With