我正在使用Async方法开发Silverlight应用程序并使用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));
}
}
答案 0 :(得分:1)
你是说你想要一个接一个地打电话给他们? 你可以从Login completed handler中调用第二个(然后是第二个从第二个完成处理程序的处理程序)。
答案 1 :(得分: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));
}
}