I’m developing a silverlight application and consuming WCF service with Async methods. But I couldnt make it working.
In my page I have the code below. Basically I want to first call LoginAsync then GetTablesAsync then GetPlayersAsync and meanwhile I need to call the client notify methods as well. How can I arrange it ? With Locks or is there a method for chaining these events to make sure that they will do fine?
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));
}
}
I have found AsyncCTP most useful for the scenario you described. However, you can achieve roughly the same readability as roughly javascript libraries if you use the following pattern: