这是我在董事会上的第一个问题。我正在使用 WCF 和 MVVM 模式编写我的第一个企业级 Silverlight (5) 应用程序。我的问题是我不明白如何让模型类调用 WCF 服务,并且(这是问题所在)在将结果返回给调用视图模型之前等待结果。
我查看了 msdn 以了解 async 和 await 关键字的用法,但我不确定需要将哪种方法标记为“async”。在我看来,服务的自动生成的 Reference.cs 文件可能需要修改,但我有疑问。更重要的是,我什至不确定我是否需要使用 async 和 await,因为我认为通过使用 WCF 应该可以正常工作。
无论如何,这是我拥有的模型类。我希望在 WCF 调用完成后执行 return 语句,但事实并非如此:
public class CRMModel
{
ObservableCollection<CarrierInfo> carrierInfoCollection = new ObservableCollection<CarrierInfo>();
public ObservableCollection<CarrierInfo> GetCarrierInformation()
{
var client = new CarrierRateService.CarrierRateServiceClient();
client.GetCarrierInformationCompleted += (s, e) =>
{
var info = e.Result;
carrierInfoCollection = info;
System.Diagnostics.Debug.WriteLine("Just got the result set: " + carrierInfoCollection.Count);
};
client.GetCarrierInformationAsync();
System.Diagnostics.Debug.WriteLine("About to return with: " + carrierInfoCollection.Count);
return carrierInfoCollection;
}
}
正如您可能猜到的那样,结果是:
即将返回:0
刚得到结果集:3
非常感谢你的帮助!弗朗西斯