I ran into a small but thought-provoking problem in my sample Silverlight database application. I wanted to call a web service, and only call a second web service if the first was successful. The problem is that all web service calls are asynchronous, so you cannot do this with a simple if statement. The quick fix I used was to store my intended operation in a PendingOperation variable. When the first web service completes, it checks for a pending operation. If the first call succeeds and finds a pending operation, it calls the second web service to complete it.
My workaround is OK, but it got me thinking about the best way of doing this. What if you had a sequence of web services to call, and wanted to check for the success of each one before proceeding to the next? I discussed this on the Silverlight forums and was directed to this article by Daniel Vaughan which describes how to do this in a background thread. I haven’t tried his code yet; but it strikes me that this could be useful; I’d like to see Microsoft build something like it into the core framework. Since all the calls take place on a background thread, there is no danger of locking up the user interface.
If RIA programming is as important as some suggest we will have to get used to this kind of problem.
I’ve written a class that makes synchronously calling WCF service in silverlight easy. It can be found here.
Since the article was written, Microsoft has provided the Task class which is useful. It proves to be a lot easier to use.
http://msdn.microsoft.com/en-us/magazine/ff959203.aspx
http://msdn.microsoft.com/en-us/library/dd460717.aspx