.NET

Using asynchronous WebService calls in Silverlight

Last I was creating a silverlight application and I thought that showing how to do some asynchonous calls to a webservice could be interesting.

 

First of all an overview of the things that you need:

  1. A Silverlight application
  2. A website where the silverlight is shown and where a webservice is created.

 

You visual studio project should look like this:

imageIn this image you can see the default content of the new created sample webservice.

 

What we gonna do is put a loading label on the silverlight page.

After that we gonna start the event that gets the “Hello world” value from the webservice.

When the result is returned we can put the result into the loading label.

 

First create a label on the xaml page.

Your page should look like this:

image

Now you need to add the webservice reference to the silverlight project.

You need to do this. Otherwise you will not be able to create a service object.

You can do so by right click the Silverlight project and add a service reference:

image

When added you can go to the code behind of the start silverlight page.

Here in the constructor you can add the event that needs to fire on startup.

You add a new ‘method’Completed event to the service object.

In this event you also specify which method need to be called with the result. (in this example it is the ‘helloWorld_Completed’ method)

 

Your code should look like this:

public partial class MainPage : UserControl
{
    private SampleService.SampleWebServiceSoapClient dataService = new SampleService.SampleWebServiceSoapClient();

    public MainPage()
    {
        InitializeComponent();

        dataService.HelloWorldCompleted += new EventHandler<sampleservice.helloworldcompletedeventargs>(helloWorld_Completed);
        dataService.HelloWorldAsync();
    }

    private void helloWorld_Completed(object sender, SampleService.HelloWorldCompletedEventArgs e)
    {
        //Sleep for 1 second to show the loading message
        Thread.Sleep(1000);

        lblResult.Content = e.Result.ToString();
    }
}

 

As you can see I added a sleep for one second so you could see the “loading…” text before seeing the result.

When you run the page now your result should look like these 2 screens:

First the loading screen:

image

The second screen (with the result) should look like this:

image

So this was a simple example for using webservices in a silverlight application.

Leave a Reply

Your email address will not be published. Required fields are marked *