2013-06-21 26 views
1

我目前正在爲需要調用WCF服務應用程序的WP7開發一個應用程序。我用一個小型的WPF應用程序測試了服務,一切都很順利。但現在,我把它從我的WP7應用程序,我係統地出現以下情況例外:CommunicationException被解除,即使在try/catch塊中

An exception of type 'System.ServiceModel.CommunicationException' occurred in 
System.ServiceModel.ni.dll but was not handled in user code 

System.ServiceModel.CommunicationException was unhandled by user code 
    HResult=-2146233087 
    Message=The remote server returned an error: NotFound. 
    Source=System.ServiceModel 
    InnerException: System.Net.WebException 
     HResult=-2146233079 
     Message=The remote server returned an error: NotFound. 
     Source=System.Windows 
     InnerException: System.Net.WebException 
      HResult=-2146233079 
      Message=The remote server returned an error: NotFound. 
      Source=System.Windows 
      InnerException: 

的異常狀態越來越儘管解除我作出這樣一個try/catch塊(在MyProjectPath內我的服務電話。 Model.User.cs):

public Task<User> Load(string logon, string pwHash) 
{ 
    TaskCompletionSource<User> tcs = new TaskCompletionSource<User>(); 

    client.GetUserByCredsCompleted += ((s, e) => 
     { 
      if (e.Error == null) tcs.TrySetResult(e.Result); 
      else 
      { 
       StringBuilder sb = new StringBuilder(); 
       sb.AppendLine("Error encountered while getting data :"); 
       sb.AppendLine(e.Error.Message); 

       MessageBox.Show(sb.ToString()); 
      } 
     }); 
    try 
    { 
     client.GetUserByCredsAsync(logon, pwHash); 
    } 
    catch (System.ServiceModel.CommunicationException ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 

    return tcs.Task; 
} 

並執行時,異常發生在這裏(在System.ServiceModel.ni.dll):

public MyProjectPath.ServiceReference.User EndGetUserByCreds(System.IAsyncResult result) { 
    object[] _args = new object[0]; 
     // Exception gets lifted by the following line : 
    MyProjectPath.ServiceReference.User _result = ((MyProjectPath.ServiceReference.User)(base.EndInvoke("GetUserByCreds", _args, result))); 
    return _result; 
} 

有沒有人已經遇到了這個問題,解決了嗎?我必須承認我在這裏很笨...

回答

0

你在調用異步API。儘管你正在將這個調用包裝在try/catch塊中,那麼這個調用可能會啓動一個新線程或排隊請求另一個現有線程進行提取。無論哪種方式,您的try/catch只會保護您免受撥打電話的線程上的異常,並且不會有任何異常。異步調用(的開始)成功,所以catch塊永遠不會生效,然後控制權被傳遞給另一個線程,這就是拋出異常的地方。

通過在try/catch中將您的調用包裝爲GetUserByCredsAsync,您無法防止EndGetUserByCreds中的異常。這兩種方法在不同的時間執行不同的線程。您需要修改EndGetUserByCreds,以便捕獲異常並正確處理它們,而不是讓它們崩潰。

+0

感謝您的提示,但是您有任何想法,爲什麼服務無法找到服務器,而WCF測試客戶端和我的WPF測試應用程序可以訪問數據沒有任何問題? 此外,我無法編輯異常被解除(或只是不知道如何)的文件,因爲它在添加服務引用時生成的dll中。 – ZipionLive

+0

好吧,我只是想出了這個片段實際上可以在Reference.cs中找到,我添加了必要的try/catch塊。現在該應用程序是穩定的...但仍然無法正常工作: - / – ZipionLive