Home > Articles > Programming > ASP .NET

Silverlight Best Practices: Asynchronous Programming

  • Print
  • + Share This
Microsoft MVP for Silverlight Jeremy Likness covers asynchronous programming techniques. Learn how to call your web services in a way that prevents performance bottlenecks or blocking on the UI thread when processing complex results, understand the differences between the event-based and asynchronous programming model, and discover techniques for handling sequential asynchronous workflows in a way that keeps your code easy to read and maintain.
Like this article? We recommend

Silverlight provides a robust networking stack with the ability to load web pages, interface with web services, and parse RSS feeds out of the box. Unlike the desktop-based framework, the Silverlight client runtime does not allow synchronous operations and requires network-based operations to be asynchronous. While asynchronous and event-based programming models have been a part of the .NET Framework since the earliest versions, orchestrating sequential and parallel asynchronous workflows can be problematic, especially when trying to maintain code readability and maintainability.

Fortunately, several best practices can be utilized to simplify and extend asynchronous processes. This article will cover several of these approaches. The right approach depends on the target audience, development team and environment, and coding style. You will also learn how to call web services from Silverlight the correct way to control whether the response returns on the UI thread.

Asynchronous Events

Events are provided by the .NET framework to allow classes to provide notifications when something interesting happens. Events use delegates as templates. The following code snippet illustrates the default template for an event:

public delegate void SomethingHappenedEventHandler(object sender, EventArgs args);

The delegate can then be used to expose the event, like this:

public event SomethingHappenedEventHandler SomethingHappened;

An event can only be invoked by the class that owns the event. This is referred to as raising the event. The class that owns the event simply calls the event and passes the sender (usually the class itself) and the event arguments that are associated with the event, like this:

SomethingHappenedEventHandler(this, EventArgs.Empty);

The class that raises this event can be referred to as the publisher. To receive notifications for an event, or to subscribe to the event, the subscriber simply attaches a delegate for the class to call when the event is raised (or published). For example, the following subscriber class creates an instance of the publisher and writes a message to the debugger whenever the “something happens” event is published:

public class Subscriber
    private readonly Publisher _publisher = new Publisher();

    public Subscriber()
        _publisher.SomethingHappened += 

    void Publisher_SomethingHappened(object sender, 
        EventArgs args)
        Debug.WriteLine("Something happened!");

Events are asynchronous because they allow the interested class to register for the event then perform other tasks until something interesting happens. When the event is published, the subscriber is notified and can then respond to the event. The event model is the default model used to invoke web services in Silverlight (the proxy that is generated when you add a service references exposes events and event arguments). Consider a web service with the following signature:

[ServiceContract(Namespace = 
public interface IMyServices
    int Add(int x, int y);

The following code is required to call the service. Note that the call is asynchronous because the code does not “wait” for the result. Instead, it registers for the event of receiving the result then begins the request. At this point, the main thread of code has stopped executing. This is because the request must be sent over to the network, received by the service, processed, and then returned to the Silverlight client. Once the request returns, the service client processes the result and raises the event.

public void CallService()
    var client = new HostServices.MyServicesClient();
    client.AddCompleted += client_AddCompleted;

void client_AddCompleted(object sender, HostServices.AddCompletedEventArgs e)

All services by default generate the complementary methods that end with Async to begin the request and raise the Completed event when the request is finished.

One immediate issue with this approach is that the model is not easy to test. The client must be created, and all of the services set up appropriately in the environment. Creating a “pretend” service requires exposing an event and processing the result. The result is highly coupled code. The subscription to the event creates a reference that can result in memory issues later because unregistered events may not be garbage-collected. The first step to fix these challenges is to decouple the code. The .NET Framework provides the perfect class to accomplish this: the Action class.

  • + Share This
  • 🔖 Save To Your Account