Your question is a little unclear (should it be count <=
?), but here goes...
What you are asking for is how to do a synchronous call. With an async call, before you make the call you assign an event handler to be called upon completion of the call, then you make the call. This means your completion code is in a different function to the code that makes the call. This means that if your async call is made on the UI thread, the UI will not block while the call is made.
Sync calls are possible in Silverlight, but you have to make sure you do not do them on the UI thread. One way to achieve this is to start a new background thread, execute the async call on the background thread, but block the return until the call has been completed. Here is a pseudo code sample:
private AutoResetEvent myResetEvent;
private void MyCallFunction(object someParameter) {
if (this.Dispatcher.CheckAccess())
{
Action<object> a = new Action<object>(MyCallFunction);
a.BeginInvoke(someParameter, null, null);
return;
}
myResetEvent = new AutoresetEvent();
myAsyncCall.CallCompleted += new EventHandler<>(myAsyncCall_CallCompleted);
myAsyncCall.DoAsyncCall(someParameter);
myResetEvent.WaitOne();
//increment your count here
}
private void myAsyncCall_CallCompleted(object sender, SomeEventArgs e) {
if (e.Error == null && !e.Cancelled) {
if (myResetEvent != null)
myResetEvent.Set();
}
}
Note that this code is not particularly thread safe or production ready - it is just a quick sample.
What happens here is that when you enter MyCallFunction
, it checks to see if it is running on the UI thread, if it is then it re-invokes itself on a background thread. It then sets up an AutoResetEvent, and makes the async call. It then pauses on the myResetEvent
object until it has been set (or 'signalled') from the call completed handler, at which point code execution continues. Note that you shouldn't attempt to access a control directly from code like this without first ensuring you are back on the UI thread.
When i started working out how to do this in Silverlight, i started with this SO post, and continued with this link. But as Marc gravell says in that first post, don't do it if you can avoid it. The only time i have needed to do this was when i needed to aggregate the results of several disparate WCF calls into one result that was returned to the UI (and these calls could not be combined in to one facade style WCF method).