Utsav
Utsav

Reputation: 1603

Make multiple async calls in a single call in C#

I want to make multiple asynchronous calls in a single call without using a loop. For example, I'd like to pass a list of URIs and and retrieve all of them asynchronously in one call. Is this possible via C#?

Here's an example in Java that does something similar to what I am looking for.

Upvotes: 2

Views: 851

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499790

You can get a list of tasks very easily - for example:

var tasks = uris.Select(async uri =>
            {
                using (var client = new HttpClient())
                {
                    return await client.GetStringAsync(uri)
                }
            })
            .ToList();

Note that if you want to use async/await, you'll need C# 5, not C# 4. You can still use .NET 4.0 if you use the Microsoft.Bcl.Async Nuget package, but you must use a C# 5 compiler.

Upvotes: 6

Related Questions