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

wcf call completed event is not fired in correct order

在我的 Silverlight 应用程序中,我将 WCF 调用放入我的 ViewModel class。

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 class 中的方法。

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

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

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

谢谢

得到解决方案,只需添加一个while循环:

            this.ViewModel.GetDateTime();

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