我正在开发一个 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));
}
}