1

我在 windows phone 7 应用程序中使用已完成和异步方法时遇到问题。

我的代码在这里:

private void messageClient_getMessageOfUserCompleted(object sender, ADRTRYST_CLIENT.LocalHostMessageService.getMessageOfUserCompletedEventArgs e)
    {
        //lstBxMessages.ItemsSource = e.Result;

        System.Collections.ObjectModel.ObservableCollection<ADRTRYST_CLIENT.LocalHostMessageService.OBJMessage> mesList = e.Result;
        foreach (ADRTRYST_CLIENT.LocalHostMessageService.OBJMessage mes in mesList)
        {
            MessageObj message = new MessageObj();
            message.Date = mes.MessageDate;
            messageList.Add(message);
            ADRTRYST_CLIENT.LocalHostMemberShipService.MemberShipSoapClient memClient = new ADRTRYST_CLIENT.LocalHostMemberShipService.MemberShipSoapClient();
            MessageBox.Show(memClient.State.ToString());
            memClient.GetUserByUserIdCompleted += new EventHandler<ADRTRYST_CLIENT.LocalHostMemberShipService.GetUserByUserIdCompletedEventArgs>(memClient_GetUserByUserIdCompleted);  
            memClient.GetUserByUserIdAsync(mes.SenderUserID);

            lstBxMessages.Items.Add(mes.MessageDate);

        }
    }


    private void memClient_GetUserByUserIdCompleted(object sender, ADRTRYST_CLIENT.LocalHostMemberShipService.GetUserByUserIdCompletedEventArgs e)
    {

        ADRTRYST_CLIENT.LocalHostMemberShipService.OBJPerson user = e.Result;
        if (user != null)
            lstBxMessages.Items.Add(user.UserName);

    }

我期望在列表框中看到消息的日期,然后是消息的发件人。但是,首先列出所有日期,然后在列表框中列出发件人姓名。我该如何解决这个问题?

4

1 回答 1

1

因为事件是异步触发的,所以 ListBox 首先被循环MessageDates中的所有内容填充。foreach如果MessageDate不是已完成事件参数的一部分,那么您可以对已完成事件使用匿名方法来用MessageDateand填充列表框User

memClient.GetUserByUserIdCompleted += (obj, e) => 
{
    if (e.Result == null)
        return;

    lstBxMessages.Items.Add(mes.MessageDate);
    lstBxMessages.Items.Add(e.Result.UserName);
}
memClient.GetUserByUserIdAsync(mes.SenderUserID);
于 2012-05-01T21:19:35.823 回答