c# - WP7 从 BeginGetResponse 回调中传播异常

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

我正在使用 HttpWebRequest 调用网络服务。如果 BeginGetResponse 的 AsyncCallback 抛出错误,我想将它传播到我的主程序流。我在执行此操作时遇到了问题,因为错误不会传播到 AsyncCallback 之外。我已经尝试在 HttpWebRequest 链的每一步放置 try/catch block ,但它从未传播到“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);
    }
}

最佳答案

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

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

ResponseCallback 何时(甚至是否)执行以及执行时 UI 线程上会发生什么是未知的。因此,ResponseCallback 将在不同的线程上执行。

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

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

关于c# - WP7 从 BeginGetResponse 回调中传播异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4420305/

相关文章:

windows-phone-7 - 当我使用 "PhotoChooserTask"并调用 Show() 时,我的项目崩溃了,我不知道。帮我

c# - 将消息从一个 C# 控制台应用程序发送到另一个

c# - 外部更新数据库时刷新网络表单

c# - XmlSerializer, "Specified"后缀和 IReflect

c# - 当调用 Flush() 时,NLog 是否应该刷新 AsyncTargetWrapper 中所有排队的消息?

c# - Silverlight:访问企业数据的最佳实践

sockets - Windows Phone 7.1 Mango 和 NetworkStream。包含在内吗?有什么好的选择吗?

Silverlight Windows Phone 7 : Load Images From URL

c# - Visual Studio 无法识别 Form.Designer.cs 文件

具有提升信任和签名证书的 Silverlight 4 OOB 应用程序不会更新?需要重新安装吗?