开发者

SilverLight WCF Response does not come back in time

This code is being used to validate if an email exists in the database. The service return the values fine because it was tested with WCF Storm. In the code I am trying to call this method which return an object (validationResponse). If validationResonse has a true key I want to throw the ValidationException. What i think is happening is SL is making the call asyn and then moving one to he next line of code. How can I call a WCF method and get its reponse and act on it?

public string email
        {
            get
            {
                return _email;
            }
            set
            {
                vc.emailAddressCompleted += new EventHandler<emailAddressCompletedEventArgs>(vc_emailAddressCompleted);
                vc.emailAddressAsync(value);

                //Fails here with a null reference to vr (vr is declared futher up)
                if (vr.isValid == false)
                {

  开发者_JS百科                  throw new ValidationException(vr.validationErrors);
                }

                this._email = value;
            }
        }

        void vc_emailAddressCompleted(object sender, emailAddressCompletedEventArgs e)
        {
            //this never gets executed
            this.vr = e.Result;
        }


In silverlight all service calls are made asynchronously, in other words you can't call the service synchronously and wait for the reply. So what is happening in your code is vr is null and the exception is being thrown before the service call returns. You could change your code to something like this:

vc.emailAddressCompleted += 
  new EventHandler<emailAddressCompletedEventArgs>(vc_emailAddressCompleted);
vc.emailAddressAsync(value);

//this while loop is not necessary unless you really want to wait 
//until the service returns
while(vr==null)
{
    //wait here or do something else until you get a return 
    Thread.Sleep(300); 
}
//if you got here it means the service returned and no exception was thrown 

void vc_emailAddressCompleted(object sender, emailAddressCompletedEventArgs e)
{
    //should do some validation here
    if (e.Error!=null) throw new Exception(e.Error.ToString());
    vr = e.Result;
    if (!vr.isValid)
    {
      throw new ValidationException(vr.validationErrors);
    }
    _email = value;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜