SilverLight WCF响应未及时返回

时间:2011-08-01 22:37:17

标签: silverlight wcf

此代码用于验证数据库中是否存在电子邮件。该服务返回值很好,因为它是使用WCF Storm测试的。在代码中,我试图调用此方法返回一个对象(validationResponse)。如果validationResonse有一个真正的键我想抛出ValidationException。我认为正在发生的是SL正在调用asyn然后将其移动到下一行代码。如何调用WCF方法并获得响应并对其进行操作?

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)
                {

                    throw new ValidationException(vr.validationErrors);
                }

                this._email = value;
            }
        }

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

1 个答案:

答案 0 :(得分:1)

在silverlight中,所有服务调用都是异步进行的,换句话说,您无法同步调用服务并等待回复。因此,代码中发生的事情vrnull,并且在服务调用返回之前抛出异常。您可以将代码更改为以下内容:

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