Reputation: 23
I have the following code:
//ids are a list of strings
foreach (string id in ids)
{
string serviceurl = "https://xxx.xx.xxx/internal/v2/idsearch?id=" + id;
List<string> lst = new List<string>();
var task = WebUtil.MakeAsyncRequest("GET", serviceurl, "application/json");
string val = task.Result;
if (val != "")
lst.Add(val);
}
public static Task<string> MakeAsyncRequest(string method,string url, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = method;
request.Timeout = 20000;
request.Proxy = null;
string clientId = ConfigManager.GetClientId;
string clientSecret = ConfigManager.GetClientSecret;
request.Headers.Add(HttpRequestHeader.Authorization, ConfigManager.GetServiceKey);
request.Headers.Add("client_id", clientId);
request.Headers.Add("client_secret", clientSecret);
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(responseStream))
{
//Need to return this response
string strContent = sr.ReadToEnd();
return strContent;
}
}
It all works fine but i am just not sure if i am implementing the async
process properly as it seems like it is doing it synchronously. I would really appreciate anyone who could help me identify what i am doing wrong...thanks!
EDIT:
Here is how i solved it....
var taskList = new List<Task<string>>();
foreach (string id in ids)
{
string serviceurl = "https://xxx.xx.xxx/internal/v2/idsearch?id=" + id;
taskList.Add(WebUtil.MakeAsyncRequest(serviceurl, "application/json"));
}
try
{
string[] val = await Task.WhenAll(taskList.ToArray());
}
catch (Exception)
{
throw;
}
public static async Task<string> MakeAsyncRequest(string url, string contentType)
{
using (HttpClient client = new HttpClient())
{
var requestMessage = new HttpRequestMessage()
{
RequestUri = new Uri(url),
Method = HttpMethod.Get,
};
// Add our custom headers
requestMessage.Headers.Add("client_id", ConfigManager.GetClientId);
requestMessage.Headers.Add("client_secret", ConfigManager.GetClientSecret);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(ConfigManager.GetServiceKey);
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
HttpResponseMessage response = await client.SendAsync(requestMessage);
var result = await response.Content.ReadAsStringAsync();
string res = result.ToString();
return res;
}
}
Upvotes: 2
Views: 2604
Reputation: 738
I suppose the best way for making an async
request is HttpClient
.
You can write something like this:
var client = new HttpClient();
var request = new HttpRequestMessage()
{
RequestUri = new Uri("xxxxxx"),
Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new ....);
var response = await client.SendAsync(request);
//read a result from the repsonse
Upvotes: 0
Reputation: 171246
ReadToEnd
is synchronous, yes. There are async equivalents.
Also note, that DNS resolution is synchronous here. This is a bug that is persistently not being fixed.
Probably, the best fix is to use HttpClient
which makes downloading a string asynchronously a one-liner.
Upvotes: 3