aybe
aybe

Reputation: 16662

Make this LINQ statement return T instead of Task<T>

I would like the following statement to return an IEnumerable of String instead.

IEnumerable<Task<string>> @select = artist.Reviews.Select(async s => await DownloadFile(s.ImageUrl,1000));

Adding await in front of DownloadFile did not change anything.

Signature of the method being called :

private static async Task<string> DownloadFile(string url, int timeout)

How can I achieve this ?

Upvotes: 2

Views: 749

Answers (2)

Ana Betts
Ana Betts

Reputation: 74654

Check out https://github.com/paulcbetts/linqtoawait, I wrote a library to address exactly this problem.

Upvotes: 4

Stephen Cleary
Stephen Cleary

Reputation: 456507

First, understand your types. That will lead you to a correct solution. I assume you're familiar with IEnumerable<T> (a sequence of things); but Task<T> is new to many people. A Task<T> is a future - some operation that will have a result of type T at some future time.

If you have an IEnumerable<Task<string>> (literally, a sequence of futures that will have string results), and you want IEnumerable<string> (literally, a sequence of strings), then what you want to do is to (asynchronously) wait for all futures to complete.

You can (asynchronously) wait for multiple futures by using Task.WhenAll:

IEnumerable<Task<string>> @select = artist.Reviews.Select(s => DownloadFile(s.ImageUrl,1000));
string[] results = await Task.WhenAll(@select);

Upvotes: 9

Related Questions