4

我正在使用 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);
    }
}
4

1 回答 1

2

我认为您对异步代码执行的工作方式以及回调执行如何与调用代码相匹配感到困惑。

GetRequestStreamCallback, 之后对该request.BeginGetResponse方法的调用将继续执行,并且在您的示例中刚刚结束。

不知道何时(或什至是否)ResponseCallback会执行,或者当它执行时 UI 线程上会发生什么。因此,ResponseCallback将在不同的线程上执行。

可以通过使用Dispatcher.BeginInvoke. 但是,您不能在另一个方法的上下文中执行此操作。

虽然我不推荐它,但您可能想看看这个关于使回调看起来同步执行的讨论。这会阻塞你的 UI 线程,所以不推荐。

于 2010-12-12T20:15:54.760 回答