简体   繁体   English

在Silverlight中,如何处理异步调用期间的错误?

[英]In Silverlight, how do I handle an error during an asynchronous call?

In my SL4 app, I have a call to a service, svc.SubmitAsync(). 在我的SL4应用中,我有一个对服务svc.SubmitAsync()的调用。 Since this is an async call, once the method is hit, my code goes on to the next line. 因为这是一个异步调用,所以一旦方法被点击,我的代码就会转到下一行。 This is fine as long as the user enters the correct user name and password. 只要用户输入正确的用户名和密码,就可以了。 If they don't, EndSubmit() throws an exception. 如果没有,则EndSubmit()引发异常。 EndSubmit() is in References.cs, part of the auto-generated Silverlight code. EndSubmit()位于References.cs中,它是自动生成的Silverlight代码的一部分。

I tried wrapping svc.SubmitAsync() in a try-catch but this is an async call and the try-catch block completes before the exception is even thrown. 我尝试将svc.SubmitAsync()包装在try-catch中,但这是一个异步调用,并且try-catch块在抛出异常之前就已完成。

How do I catch this error? 如何捕获此错误?

Thanks! 谢谢!

Update 1 更新1

public void SubmitTweetAsync(TestSilverlightApp.svc.Tweet tweet, object userState) {
            if ((this.onBeginSubmitTweetDelegate == null)) {
                this.onBeginSubmitTweetDelegate = new BeginOperationDelegate(this.OnBeginSubmitTweet);
            }
            if ((this.onEndSubmitTweetDelegate == null)) {
                this.onEndSubmitTweetDelegate = new EndOperationDelegate(this.OnEndSubmitTweet);
            }
            if ((this.onSubmitTweetCompletedDelegate == null)) {
                this.onSubmitTweetCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnSubmitTweetCompleted);
            }
            base.InvokeAsync(this.onBeginSubmitTweetDelegate, new object[] {
                        tweet}, this.onEndSubmitTweetDelegate, this.onSubmitTweetCompletedDelegate, userState);
        }

Update 2 - This is a WCF service. 更新2-这是WCF服务。

You have to check the Error field in the parameter you receive in the handler. 您必须检查在处理程序中收到的参数中的“错误”字段。

private void Client_SubmitCompleted(object sender, SubmitCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        //...
    }
    else if (e.Error != null)
    {
        // the service operation threw an exception
        throw e.Error;
    }
    else
    {
        //...
    }

It would normally be the matching completed event that has the try/catch for any exceptions. 通常,匹配完成事件具有对任何异常的try / catch。

As is it an async operation, it does not know if it succeeded or failed until it completes but it will complete in either case. 由于它是异步操作,它不知道它是成功还是失败,直到完成为止,但是无论哪种情况都将完成。

The object passed to you Completed event handler will need to hold the error message. 传递给您的Completed事件处理程序的对象将需要保存错误消息。

For example 例如

public void OnSubmitCompleted(TweetOperation op) { if(op.ErrorMessage != null) //handle the error public void OnSubmitCompleted(TweetOperation op){if(op.ErrorMessage!= null)//处理错误

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM