Communicating Asynchronously

The first thing you need to be aware of when attempting any server communication in Silverlight is that it must be performed asynchronously. The Silverlight team made the decision to not support synchronous communication in order to avoid service/HTTP/socket calls blocking the Silverlight application's user interface (and in turn, the browser, as Silverlight runs in the browser's user interface thread) while waiting for a response. Regularly hanging the browser would not make Silverlight a good plug-in citizen. Therefore, you will need to become accustomed to asynchronous programming. This typically involves making a call to the server, and waiting for an event to be raised indicating that the call is complete. The call will be performed on a background thread and return immediately, preventing the user interface from being blocked while the call is made.

Developers tend to prefer making synchronous calls when calling web services, and the like, despite the fact that it blocks the user interface while it waits for the results to be returned (resulting in a poor user experience). If you're a developer used to writing only synchronous code, asynchronous programming will require you to think a little differently in how you structure the flow of your code. However, it will no doubt make you a better developer as a result.

images Note As a general rule, if an asynchronous call raises an event when it completes, the event will usually be raised on the user interface thread. However, if it uses an asynchronous callback delegate (taking an AsyncCallback object as a parameter instead), the callback method will be executed on a background thread. The problem with the callback method executing on a background thread is that you can update the user interface only from the user interface thread. Therefore, if you want to update the user interface from a callback method, you will need to invoke the code that performs the update on the user interface thread, using the BeginInvoke method of the Dispatcher object for the view you're updating. Otherwise, you will encounter cross-thread synchronization issues, which result in an exception being thrown. To avoid this complexity, if a Completed event is available, update the user interface from it instead.

Throughout this chapter, you'll see how you can effectively perform asynchronous calls. RIA Services provides some patterns that make asynchronous programming much simpler, and we'll also touch on using inline (anonymous) methods to handle events, which you might prefer over creating a dedicated event handler method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset