views:

76

answers:

2

Everyone knows that in Silverlight all wcf service calls are asynchronous. But what can we say about the timing of the requests? For the following code, is it always true that "Hello A" will be received by the server before "Hello B"?

ServiceClient proxy = new ServiceClient();
ServiceClient proxy2 = new ServiceClient();

proxy.SayHelloAsync("Hello A");
proxy2.SayHelloAsync("Hello B");

I ran the code repeatedly and the server always received "Hello A" first. Was it just by luck?

A: 

Yes, if you have two async calls, you can have any of them finishing first.

If you need to wait any to finish, you should take a look on WaitHandle

Rubens Farias
A: 

It was just luck. I've run almost exactly the same test, and had them finish in a variety of diferent orders. This is especially true in real-world scenarios, where you might have a large number of outstanding calls going on simultaneously (for instance, in a chat application). If you need call A to finish before call B, you'll need to chain them in some fashion, and none of the mechanisms for doing so are very clean. The recommendation to use a WaitHandle of some sort can be dangerous, in my experience. Your mileage may vary, but what I've found is that if you're not very careful, using a WaitHandle to manage the timing of WCF calls can stop critical threads from functioning. It's better, though more complicated, to make your call to "B" from a method that's called when "A" is completed.

Ken Smith
I agree with your analysis of WaitHandle, it needs more care. In many cases you are probably right that chaining is better however that can expensive if the two calls could have run in parallel. Using a couple of waithandles on a specifically allocated Background thread (I.e one that has nothing else critical todo) should be reasonably simple.
AnthonyWJones
That's my understanding too, but I also know that Silverlight occasionally does some weird things by marshaling WCF calls onto the UI thread. The last time I tried to simplify my code by using a pseudo-synchronous pattern with a ManualResetEvent, I couldn't get it to work reliably: the calls would never return. But I don't remember the exact approach I was taking, and someone who understands more about threading issues than I do might have better luck :-).
Ken Smith