Multithreaded Web Service Consumption

When a client application needs to make calls to a web service for data and other business operations, some of those operations and data retrievals can take a long time. Any number of factors can contribute to a web service call taking a long time to return, including data volume, processing cost on the server, or even server load and slow network connections.

Multithreaded web service consumption has changed slightly since the previous versions of the .NET Framework. In version 2.0 of the framework, you invoke an xxAsynch() method where xx is the name of the server-side method. When the asynchronous method completes, the xxCompleted event will be triggered. All you have to do is handle the xxCompleted event and you will be consuming the web service asynchronously.

To see how to consume a web service in a background thread so that the foreground thread (user interface) can continue uninterrupted, create a new Windows Forms application and add a web reference to any web service of your choice.

Next, add two buttons to your form: one to consume the service synchronously and one to consume the service asynchronously. The code in Listing 38.4 illustrates how to consume the service synchronously and asynchronously.

Listing 38.4. Synchronous and Asynchronous Web Service Consumption

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace ThreadedConsumer { public partial class Form1 : Form {     localhost.Service svc = null;     public Form1()     {         InitializeComponent();         svc = new localhost.Service();         svc.SlowMethodCompleted +=             new ThreadedConsumer.localhost.SlowMethodCompletedEventHandler( svc_SlowMethodCompleted);     }     void svc_SlowMethodCompleted(object sender,         ThreadedConsumer.localhost.SlowMethodCompletedEventArgs e)     {         toolStripStatusLabel1.Text = "Asynch method completed.";         MessageBox.Show(e.Result);     }     private void button2_Click(object sender, EventArgs e)     {         MessageBox.Show(svc.SlowMethod());     }     private void button1_Click(object sender, EventArgs e)     {         svc.SlowMethodAsync();         toolStripStatusLabel1.Text = "Started Asynchronous method...";     } } } 

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: