1.
Why parallel api call?
If
the page needs to make multiple web requests (multiple api calls), we might end
up in page performance issue (page load time might be higher) if the one of the
api is taking longer time and blocking the other of the api calls.
I
had also encountered page load time issue in one of my project. Page was
consuming 12 different api, 4 api calls were taking longer time (more than a
minute) and blocking the execution of the other of the api calls.
To
overcome the above issue, I have made use of async and await keywords of C# and
Parallel.ForEach method where there were multiple api calls inside for each.
2. Overview of the parallel implementation
In
an async method, tasks are started when they’re created. The await operator
is applied to the task at the point in the method where processing can’t
continue until the task finishes.
var result = await WebRequest(url);
In
the above example task is waited as soon as it is created, however you can separate
creating the task from awaiting the task if your program has some other task to
accomplish in between that doesn’t depend on the completion of the task.
//
The following line creates and starts the task.
var
task1 = WebRequest(url);
// While the task is running, you can do other
work that doesn't depend
// on the results of the task1.
// the application of
await suspends the rest of this method until the task is complete.
var
result = await task1;
1. Sample example of
parallel api call.
Below program starts three asynchronous web api calls and
then awaits them in the order in which they’re called. Below web request don’t
always finish in the order in which they’re created and awaited. They start to run
when they’re created, and one or more of the tasks might finish before the
method reaches the await expressions.
private async
Task<int> GetTotalContentLenght()
{
HttpClient
webClient = new HttpClient();
Task<int> webRequest1 =
GetContentLength("http://msdn.microsoft.com", webClient);
Task<int> webRequest2 = GetContentLength("Url",
webClient);
Task<int> webRequest3 =
GetContentLength("Url", webClient);
int
length1 = await webRequest1;
int
length2 = await webRequest2;
int
length3 = await webRequest3;
int totalLength
= length1 + length2 + length3;
return totalLength;
}
async
Task<int> GetContentLength(string url, HttpClient client)
{
var byteArray = await
client.GetByteArrayAsync(url);
return
byteArray.Length;
}
2. Paralle.ForEach
List<string>
urls = new List<string> {
"URL 1",
"URL2", "URL
3", "URL 4", "URL 5" };
Parallel.ForEach(urls, async m =>
{
byte[] urlContents = GetURLContentsAsync(url); //web api call
int
total+= await urlContents.Length;
});
3.
References
1.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await
No comments:
Post a Comment