我有一个方法
private string MakeRequest
之前已经返回了一个字符串,但现在我在这个方法中有一个异步操作。
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();
}
}
如何将字符串从上次回调返回到MakeRequest?
答案 0 :(得分:2)
如果您使用的是.NET 4.5,则可以利用Task
中基于WebRequest
的方法:
public async Task<string> MakeRequest()
{
var request = WebRequest.Create(url);
var postStream = await request.GetRequestStreamAsync();
// 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();
var response = (HttpWebResponse)(await request.GetResponseAsync());
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();
return trimResponseString;
}
}
如果你从一个非本身异步的上下文中调用它,你可以调用这个方法,然后同步等待结果:
string result = MakeRequest().GetAwaiter().GetResult();