即使在try / catch块中,CommunicationException也会被解除

时间:2013-06-21 10:32:41

标签: c# .net wcf windows-phone-7

我目前正在开发一个需要调用WCF服务应用程序的WP7应用程序。我使用一个小型WPF应用程序测试了该服务,一切都很顺利。但是现在我从我的WP7应用程序中调用它,我系统地得到以下异常:

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

有没有人遇到过这个问题并解决了吗?我必须承认我在这里很无能......

1 个答案:

答案 0 :(得分:0)

您正在调用异步API。虽然您将该调用包装在try / catch块中,但该调用可能会启动一个新线程或将另一个现有线程的请求排队。无论哪种方式,你的try / catch只能保护你免受发出调用的线程抛出的异常,而且没有任何异常。你的异步调用的(开始)成功就好了,所以catch块永远不会生效,然后控制被传递给另一个线程,这就是抛出异常的地方。

通过在try / catch中包含对GetUserByCredsAsync的调用,无法防止EndGetUserByCred中的异常。这两种方法在不同的时间执行不同的线程。您需要修改EndGetUserByCreds,以便它捕获异常并适当地处理它们,而不是让它们使线程崩溃。