C
C#15mo ago
kocha

✅ Why do my ASP.NET Core Requests not run in parallel?

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/slow", async () => await Task.Delay(5000));
app.Run();
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/slow", async () => await Task.Delay(5000));
app.Run();
If I call the /slow enpoints multiple times in short succession, I can see that they are not processed in parallel. I can see that because they take longer than 5 seconds (except first one). This is confusing to me, as I would expect them to await the delay in parallel. Can someone explain why this is?
12 Replies
Tvde1
Tvde115mo ago
app.MapGet("/test",
async () =>
{
using var httpClient = new HttpClient();
var requests = new List<Task>();

var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
var response = httpClient.GetAsync("http://localhost:5800/slow");
requests.Add(response);
}

await Task.WhenAll(requests);
stopwatch.Stop();
return Results.Ok($"Took {stopwatch.ElapsedMilliseconds}ms");
});
app.MapGet("/test",
async () =>
{
using var httpClient = new HttpClient();
var requests = new List<Task>();

var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
var response = httpClient.GetAsync("http://localhost:5800/slow");
requests.Add(response);
}

await Task.WhenAll(requests);
stopwatch.Stop();
return Results.Ok($"Took {stopwatch.ElapsedMilliseconds}ms");
});
"Took 5125ms" they run in parallel on my pc at least
kocha
kochaOP15mo ago
yes, this also runs parallel on my pc, but have you tried my example?
Tvde1
Tvde115mo ago
yes, I added that to your example it calls your example
Tvde1
Tvde115mo ago
No description
kocha
kochaOP15mo ago
ahh, i see
kocha
kochaOP15mo ago
my logs tell me the request took 5 seconds, but they clearly take longer
No description
Tvde1
Tvde115mo ago
how are you measuring how long they take?
kocha
kochaOP15mo ago
i start two requests at the same time and see if they finish at the same time, but one of the two take roughly double the time hmm, if i test with your code it also takes 5000, it only happens if i send the requests with my browser
Tvde1
Tvde115mo ago
Does this answer the question?
Tvde1
Tvde115mo ago
Stack Overflow
Web api handles just 6 concurrent requests
I have a web api project using async/await controllers and tasks. I've noticed every request after the 6th one gets queued. To test this, I made an easy delayed action: [HttpGet()] [Route("
Tvde1
Tvde115mo ago
the browser limits the amount of concurrent requests :p
kocha
kochaOP15mo ago
yes, but i just open the url in 2 seperate tabs ok, tested it with postman, they run in parallel so it is a browser thing

Did you find this page helpful?