Windows Phone, Web服务和捕获异常

本文关键字:捕获异常 服务 Web Phone Windows | 更新日期: 2023-09-27 18:10:25

我在Windows Phone中有以下代码:

public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    private void Button_LogIn_Click(object sender, RoutedEventArgs e)
    {
        Service1SoapClient web_service = new Service1SoapClient();
        web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
        web_service.LogInCompleted += new EventHandler<LogInCompletedEventArgs>(login_complete);
    }
    private void login_complete(object obj, ClientWebService.LogInCompletedEventArgs e)
    {
        string answer = e.Result.ToString();
        if (answer.Equals("Success") || answer.Equals("success"))
        {
            NavigationService.Navigate(new Uri("/Authenticated.xaml", UriKind.Relative));
        }
        else
        {
            MessageBox.Show("The log-in details are invalid!");
        }
    }
}

代码使用web服务来让用户登录到系统。登录系统正常工作

我的问题是,我应该在哪里插入try catch语句,以便在web服务未运行时捕获异常?我在button_click事件处理程序中尝试过,但无济于事,甚至在我获得结果时也行。

Windows Phone, Web服务和捕获异常

不清楚您的Service1SoapClient基于什么类型,因此下面的语句可能不准确。由于传入了用户名和密码并返回了其他一些状态,因此您似乎没有使用移动服务客户端。

然而,LoginAsync方法名上的...Async后缀表明该API返回Task<T>,这意味着该API是为c# 5的新asyncawait关键字使用而构建的。

因此,我建议将你的代码修改如下:' ' '公共部分类MainPage: PhoneApplicationPage{公共主页(){InitializeComponent ();}
private async void Button_LogIn_Click(object sender, RoutedEventArgs e)
{
    try
    {
        Service1SoapClient web_service = new Service1SoapClient();
        string answer = await web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
        if (answer.ToLower().Equals("success"))
        {
            NavigationService.Navigate(new Uri("/Authenticated.xaml", UriKind.Relative));
        }
        else
        {
            MessageBox.Show("The log-in details are invalid!");
        }
    catch (<ExceptionType> e)
    {
        // ... handle exception here
    }
}

}' ' '

请注意,asyncawait的一个附带好处是,它们允许您逻辑地编写代码,包括异常处理代码,在asyncawait之前,这些代码很难正确编写!