【问题标题】:WP7 Propogate exception from BeginGetResponse callbackBeginGetResponse 回调中的 WP7 传播异常
【发布时间】:2011-05-24 03:32:43
【问题描述】:

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

【问题讨论】:

    标签: c# silverlight windows-phone-7 httpwebrequest asynccallback


    【解决方案1】:

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

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

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

    使用Dispatcher.BeginInvoke 可以让回调中的代码在 UI 线程上运行(您需要这样做才能与 UI 交互)。但是,您不能在另一个方法的上下文中执行此操作。

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

    【讨论】:

      猜你喜欢
      • 2011-11-13
      • 1970-01-01
      • 2013-01-11
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 2017-02-15
      相关资源
      最近更新 更多