Windows Phone 7应用程序中的已完成和异步方法

时间:2012-05-01 20:16:45

标签: c# windows-phone-7

我在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);

    }

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

1 个答案:

答案 0 :(得分:1)

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

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

    lstBxMessages.Items.Add(mes.MessageDate);
    lstBxMessages.Items.Add(e.Result.UserName);
}
memClient.GetUserByUserIdAsync(mes.SenderUserID);