4

我正在使用HttpWebRequest來調用Web服務。如果來自BeginGetResponse的AsyncCallback引發錯誤,我想將它傳播到我的主程序流程中。我在這樣做時遇到了麻煩,因爲錯誤不會傳播到AsyncCallback之外。我試過在HttpWebRequest鏈的每一步放置try/catch塊,但它永遠不會傳播超出「ResponseCallBack」方法。是否有可能回到主線程?WP7從BeginGetResponse回調中傳播異常

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); 
    } 
} 

回答

2

我認爲你得到困惑的方式異步代碼exectution工作原理和回調執行適合在與調用代碼。

GetRequestStreamCallback之內,在對request.BeginGetResponse的調用之後,該方法將繼續執行,並在您的示例中結束。

不知道什麼時候(或者甚至)ResponseCallback將會執行,或者當UI線程執行時會發生什麼。因此,ResponseCallback將在不同的線程上執行。

通過使用Dispatcher.BeginInvoke,可以在UI線程(您需要與UI進行交互時需要做的事)上執行回調代碼。但是,您不能在另一種方法的上下文中執行此操作。

儘管我不會推薦它,但您可能需要查看this discussion以使回調顯示爲同步執行。這會阻止你的UI線程,所以不推薦。