I have a method
private string MakeRequest
which has returned me a string earlier, but now I have in this method an async operation.
request.BeginGetRequestStream(GetRequestStreamCallback, request);
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
var postStream = request.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(request.Connection);
// Write to the request stream.
postStream.Write(byteArray, 0, request.Connection.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(GetResponseCallback, request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
var streamResponse = response.GetResponseStream();
using (var streamRead = new StreamReader(streamResponse))
{
var responseString = streamRead.ReadToEnd();
var trimResponseString = responseString.Trim(); // I need this string to return from MakeRequest
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
allDone.Set();
}
}
How can I return the string from last callback to MakeRequest?
WebRequest.GetRequestStreamAsyncreturns a Task, you can await that. Not sure what you are calling from but if its WPF, WinForms, asp.net your entry can be marked asasyncwith return of some form ofTask. You can then await theGetRequestStreamAsync