Reputation: 295
I have a WebAPI function which performs a loop calculation to find a single numerical value.
From my client side javascript, I make around 20 simultaneous requests to this function for a single page load. I have confirmed through Chrome's network performance tool that all the requests are made at the same time but the requests receive responses sequentially (the initial ones take .2 seconds, with the later ones taking up to 8s) so the server appears to be the bottleneck.
I have tried optimizing my code by making it async, though I'm not sure I did it correctly or that it improved the performance at all.
[HttpGet]
public async Task<double> CalcResult(double First, double Second)
{
var result = await Task.Run(()=>LoopCalculationFunction(First,Second));
return result * 100;
}
Is this done properly and is there any way I can further optimize this function?
Upvotes: 1
Views: 323
Reputation: 39277
You should change your client-side javascript to batch calls up, ideally into a single request. Pass an array of first
and second
values and get an array back.
1) Each round-trip is slow, you can make it faster with a single round-trip.
2) You will hit browser per-server (or per-profile) limits for simultaneous connections.
3) This isn't an appropriate use of Task.Run
, see http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html
4) If your total connection time is too large you should move to a polling API: post the calculation request and then poll for progress and the eventual result.
Upvotes: 4