0

我正在开发一个 Silverlight 应用程序并使用 Async 方法使用 WCF 服务。但我无法让它工作。

在我的页面中,我有下面的代码。基本上我想先调用 LoginAsync 然后 GetTablesAsync 然后 GetPlayersAsync 同时我还需要调用客户端通知方法。我该如何安排?使用 Locks 还是有一种方法可以链接这些事件以确保它们能够正常运行?

public partial class Root : UserControl
{
    private object syncRoot = new object();
    ServiceClient client;

    ObservableCollection<Table> Tables { get; set; }
    ObservableCollection<Player> Players { get; set; }
    public Root()
    {
        InitializeComponent();

        Tables = new ObservableCollection<Table>();

        txtLogs.Text += "\n";

        client = Helpers.GetServiceClient();

        client.NotifyReceived += new EventHandler<NotifyReceivedEventArgs>(client_NotifyReceived);

        client.PublishCompleted += new EventHandler<AsyncCompletedEventArgs>(client_PublishCompleted);
        client.SubscribeCompleted += new EventHandler<AsyncCompletedEventArgs>(client_SubscribeCompleted);
        client.GetTableListCompleted += client_GetPokerTablesCompleted;



        this.Loaded += Root_Loaded;
    }

    void Root_Loaded(object sender, RoutedEventArgs e)
    {
        NewUser newUser = new NewUser();
        newUser.Closed += newUser_Closed;
        newUser.Show();
    }

    void newUser_Closed(object sender, EventArgs e)
    {
        NewUser n = sender as NewUser;
        player = new Player
        {
            PlayerName = n.txtPlayerName.Text,
        };

        lock (syncRoot)
        {

            try
            {
                client.GetTableListAsync();
            }
            catch (TimeoutException ex)
            {

            }
            catch (CommunicationException ex)
            {

            }
        }


        lock (syncRoot)
        {
            client.LoginCompleted += client_LoginCompleted;
            client.LoginAsync(player.PlayerName);
            // publish player logged in
            client.PublishAsync(String.Format("{0} is logged in", player.PlayerName));
        }


    }
4

2 回答 2

1

你的意思是你要一个接一个地叫他们?您可以从 Login completed 处理程序中调用第二个(然后从处理程序中调用第三个以完成第二个等)。

于 2012-09-09T14:03:16.837 回答
0

我发现 AsyncCTP 对于您描述的场景最有用。但是,如果您使用以下模式,则可以实现与大致 javascript 库大致相同的可读性:

NewUser newUser = new NewUser();
newUser.Show();
newUser.Closed += (object sender, EventArgs e) =>
{
    player = new Player
    {
        PlayerName = newUser.txtPlayerName.Text,
    };

    // you aren't going to be able to catch timeout
    // errors in async method calls
    client.GetTableListAsync();

    // we can initiate login even if TableList isn't loaded yet
    client.LoginAsync(player.PlayerName);
    client.LoginCompleted += (s2, e2) => {
        // publish player logged in
        client.PublishAsync(String.Format("{0} is logged in", player.PlayerName));
    }
}
于 2012-09-10T11:46:12.303 回答