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.
HttpClientandawaitif you can - it's much more concise.GetRequestStreamthen you must callGetResponseto get the response. If you want an asynchronous response usingBeginGetResonse, then you must callBeginGetRequeststreamto get the request stream.