Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, May 16, 2018 8:29 PM
Below is my working code and i wanted to make this a parallel request. assume i have 1000 records from my dataset and i would need to process the 5 requests at a time. Basically need to do parallel request. Any sample code to achieve based on my structure would be highly appreciable. I would need result back from the each API call to update it on the back end
Below is my working code and i wanted to make this a parallel request. assume i have 1000 records from my dataset and i would need to process the 5 requests at a time. Basically need to do parallel request. Any samplecode to achieve based on my structure would be higjly appreciable.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Test
{
internal class Program
{
private static HttpClient client = new HttpClient();
private static void Main(string[] args)
{
Test1().Wait();
}
private static async Task Test1()
{
try
{
//Cache this somewhere
client.BaseAddress = new Uri("https://TestCompany.com/api/");
//Configure basic auth
var token = Encoding.ASCII.GetBytes("qxxWWVHqSPKlKNbBmHno1Q:voeCmQXwSBeLGtE5VIiNmQ");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(token));
//Note that this sets it for all requests, if you only need this for some requests then you have to use HttpRequestMessage instead
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/vnd.TestCompany+json; version=3;");
//Make an API call, using Newtonsoft to convert the data
var data = new PNotification()
{
audience = new Audience()
{
named_user = new List<string>() { "sedrfrqfhos" }
},
notification = new Notification()
{
alert = "Alert"
},
device_types = new List<string>() {
"all"
}
};
var response = await client.PostJsonAsync("push", data, CancellationToken.None).ConfigureAwait(false);
var pushResults = await response.HandleJsonAsync<PResponse>(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
}
}
}
public class Audience
{
public List<string> named_user { get; set; }
}
public class Notification
{
public string alert { get; set; }
}
public class PNotification
{
public Audience audience { get; set; }
public Notification notification { get; set; }
public List<string> device_types { get; set; }
}
public class PResponse
{
public bool ok { get; set; }
public string operation_id { get; set; }
public List<string> push_ids { get; set; }
public List<string> message_ids { get; set; }
public List<string> content_urls { get; set; }
}
public static class HttpClientExtensions
{
public static Task<HttpResponseMessage> PostJsonAsync<T>(this HttpClient source, string resourceUrl, T data, CancellationToken cancellationToken)
{
var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
return source.PostAsync(resourceUrl, content, cancellationToken);
}
public static async Task<T> HandleJsonAsync<T>(this HttpResponseMessage source, CancellationToken cancellationToken)
{
source.EnsureSuccessStatusCode();
if (source.StatusCode == HttpStatusCode.NoContent ||
source.Content == null)
return default(T);
//Should probably verify it is JSON too...
var str = await source.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!String.IsNullOrEmpty(str))
return JsonConvert.DeserializeObject<T>(str);
return default(T);
}
}
}
All replies (4)
Friday, May 18, 2018 2:45 AM âś…Answered
Hi born2win,
thank you for the reply and the API is from third party. I will need to call that in console application. any samples how to make this as parallel request
You can try the Parallel.ForEach or the HttpClient.GetAsync.ContinueWith.
For more deailed, please refer the following threads.
Paralell.ForEach with HttpClient and ContinueWith
https://stackoverflow.com/questions/19383910/paralell-foreach-with-httpclient-and-continuewith
Parallel http requests
https://stackoverflow.com/questions/13155052/parallel-http-requests
Best Regards,
Yong Lu
Thursday, May 17, 2018 7:06 AM
Hi grafic,
Below is my working code and i wanted to make this a parallel request. assume i have 1000 records from my dataset and i would need to process the 5 requests at a time. Basically need to do parallel request. Any sample code to achieve based on my structure would be highly appreciable. I would need result back from the each API call to update it on the back end
If your API is an ASP.NET Web API, you can implement the batch in your Web API. Then, you can process the 5 requests at a time.
The default Web API batch implementation is based on the mime/multipart content type. It accepts mime/multipart requests containing multiple HTTP Requests and processes all the requests sending a mime/multipart response containing the individual responses.
You can refer the following article.
Introducing batch support in Web API and Web API OData
https://blogs.msdn.microsoft.com/webdev/2013/11/01/introducing-batch-support-in-web-api-and-web-api-odata/
Best Regards,
Yong Lu
Thursday, May 17, 2018 4:58 PM
Hi Yohanan,
thank you for the reply and the API is from third party. I will need to call that in console application. any samples how to make this as parallel request.
Friday, May 18, 2018 1:36 PM
thanks for the suggestions. i will look into it.