wcf调用完成事件未按正确顺序激发

本文关键字:顺序 调用 事件 wcf | 更新日期: 2023-09-27 17:57:57

在Silverlight应用程序中,我将WCF调用放在ViewModel类中。

DateTime CurrentDateTime;
internal void GetDateTime()
{
    var client = new WcfClient();
    client.GetCurrentDateTimeCompleted += GetCurrentDateTimeCompleted;
    client.GetCurrentDateTimeAsync();
}
private void GetCurrentDateTimeCompleted(object sender, GetCurrentDateTimeCompletedEventArgs args)
{
     try
     {
          CurrentDateTime = args.Result;
     }

然后在我的代码隐藏代码some.xaml.cs文件中。我有一个复选框点击事件。

    private void CheckBox_Clicked(object sender, RoutedEventArgs e)
    {
        var msgBoxControl = new MessageBoxControl();
                msgBoxControl.Closed -= MessageBoxYesNo_Closed;
                msgBoxControl.Closed += MessageBoxYesNo_Closed;

在方法MessageBoxYesNo_Closed中,我调用ViewModel类中的方法。

private void MessageBoxYesNo_Closed(object sender, EventArgs e)
{
    try
    {
        this.ViewModel.GetDateTime();
        curDateTime = this.ViewModel.CurrentDateTime;

我的问题是,有时curDateTime = this.ViewModel.CurrentDateTime;行是在wcf调用完成方法之前执行的,所以我无法获得正确的值。

我猜可能有两个线程,一个在UI中,另一个在服务调用中?请不要使用async/await,因为我必须使用VisualStudio2010。

感谢

wcf调用完成事件未按正确顺序激发

获取解决方案,只需添加while循环:

            this.ViewModel.GetDateTime();
            while (true)
            {
                this.ViewModel.CurrentDateTime = DateTime.Now;
                if (this.ViewModel.CurrentDateTime != DateTime.MinValue)
                    break;
            }
            curDateTime = this.ViewModel.CurrentDateTime;