I am trying to make asynchronous call to some server so that the main thread does not stop for the request.
I created my request something like this :
//Create Request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = method;
request.ContentType = "application/XML";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
try
{
using (Stream requestStream = request.GetRequestStream())
{
// Send the data.
requestStream.Write(bytes, 0, bytes.Length);
}
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
if (callback != null)
{
callback(response.GetResponseStream());
}
}
}, null);
}
catch (Exception ex)
{
//TODO: Log error
}
But still the thread stops for some time in this request. Especially on the line using
(Stream requestStream = request.GetRequestStream())
Is there any way by which we can make it completely asynchronous or some other better way so that our main thread does not hangs for this request.
3 Answers 3
using (HttpClient client = new HttpClient())
{
var content = new StringContent(data, Encoding.UTF8, "application/xml");
var response = await client.PostAsync(uri, content);
var respString = await response.Content.ReadAsStringAsync();
}
-
I am little confused here. In the request we actually wait for the response by putting await. Also if method A() makes the request then we have to call by await task A() and then wait for the response. Making it synchronous only.user2692032– user26920322014年10月01日 06:13:09 +00:00Commented Oct 1, 2014 at 6:13
-
@user2692032 What Happens in an Async MethodEZI– EZI2014年10月01日 07:16:31 +00:00Commented Oct 1, 2014 at 7:16
Need to use the async methods and await them.
using (var stream = await request.GetRequestStreamAsync())
{
await stream.WriteAsync(bytes, 0, bytes.Length);
}
Here is a simple sample which I am using to make async request. Mark your method with async keyword
using (var httpClient = new HttpClient())
{
string requestContent = string.Empty; // JSON Content comes here
HttpContent httpContent = new StringContent(requestContent, Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(Verb, url);
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequestMessage.Content = request.Verb == HttpMethod.Get ? null : httpContent;
response = httpClient.SendAsync(httpRequestMessage);
var responseContent = await response.Result.Content.ReadAsStringAsync();
}
Explore related questions
See similar questions with these tags.
HttpClient
andawait
if you can - it's much more concise.GetRequestStream
then you must callGetResponse
to get the response. If you want an asynchronous response usingBeginGetResonse
, then you must callBeginGetRequeststream
to get the request stream.