我正在使用 HttpWebRequest 来调用 Web 服务。如果 BeginGetResponse 的 AsyncCallback 引发错误,我想将其传播到我的主程序流。我在执行此操作时遇到了麻烦,因为错误不会传播到 AsyncCallback 之外。我尝试在 HttpWebRequest 链的每个步骤中放置 try/catch 块,但它永远不会传播到“ResponseCallBack”方法之外。是否有可能将其返回到主线程?
private void StartRequest()
{
// Code to create request object is here
// ...
httpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), httpRequest);
}
private void GetRequestStreamCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
// End the operation
var postStream = request.EndGetRequestStream(result);
string body = GenerateRequestBody();
// Convert the string into a byte array
byte[] postBytes = Encoding.UTF8.GetBytes(body);
// Write to request stream
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
// Start the asynchronous operation to get the resonse
try
{
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}
catch (Exception)
{
throw;
}
}
private void ResponseCallback(IAsyncResult result)
{
string contents = String.Empty;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
contents = reader.ReadToEnd();
}
// Check the status
if (response.StatusCode == HttpStatusCode.OK)
{
//EXCEPTION NEVER MAKES IT PASSED HERE, EVEN IF I HAVE IT IN A TRY/CATCH BLOCK AND RE-THROW IT.
_object = ProcessResponseEntity(contents);
}
}