In their docs and examples, Microsoft says not to Mix calls to Sync and Async methods for the same HttpWebRequest (https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.begingetresponse?redirectedfrom=MSDN&view=net-5.0#remarks)
However, in the example given, they call request.BeginGetRequestStream, and in the callback they complete getting the stream using request.EndGetRequestStream, then synchronously fills it with the user input, then continue with request.BeginGetResponse.
Is it okay to just call request.GetRequestStream, fill it up with the content of another stream using CopyTo, then continue to the request.BeginGetResponse?
For example, which is better:
Option 1:
void SendRequest()
{
// here comes the creation of a request using WebRequest.CreateHttp()
// ...
request.Method = "POST";
request.BeginGetRequestStream(GetRequestStreamCallback, request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
this.someBodyContentStream.CopyTo(postStream);
postStream.Close();
request.BeginGetResponse(GetResponseCallback, request);
}
or Option 2:
void SendRequest()
{
// here comes the creation of a request using WebRequest.CreateHttp()
// ...
request.Method = "POST";
Stream postStream = request.GetRequestStream();
this.someBodyContentStream.CopyTo(postStream);
request.BeginGetResponse(GetResponseCallback, request);
}
Update
Is it possible that a call to a Begin... method that takes a callback and an object and returns an IAsyncResult will call the callback on the same thread, thus, if not handled correctly, will cause a hang in case the callback releases a wait-handle?