In many cases we may use asynchronous calls WEBSERVICE. The benefits of asynchronous are non-blocking methods. Of course, there is also a certain programming difficulty. Using asynchronous programming, we can implement the calls, query call status, or cancel calls such as remote services. We are explained as an example as an example, first establish a WebService using VS2K3, assuming is a service providing stock information. Here I deal with the relatively simple, just the time to simulate the service call takes a long time. A summary description of Namespace stockService {///
INITIALIZECMOMPONENT ();
#Region component designer generated code // Web service designer essential private icontainer components = null; ///
///
[WebMethod] public double getStockPrice (String stocksymbol) {// Here we conduct analog processing, thread pause 5 second Thread.Sleep (5000); return new random (). Nextdouble () 15.0;} [webmedhod] public double getStockPrice1 (String stocksymbol) {// Here we use the simulation process, thread pause 5 second Thread.Sleep (5000); return new random (). Nextdouble () 15.0;} [WebMethod] public double getStockPrice2 (String stocksymbol) {/ / Here we conduct analog processing, thread pause 5 second Thread.Sleep (5000); return new random (). Nextdouble () 15.0;}
}} Then we build a WinForm program to act as the client calling the WebService just established. Here we have many ways to achieve asynchronous calls (including the establishment of a thread to call the service. When the service is complete, use Delegate to implement the callback of the event). This approach let us exclude. Because when you add a web reference to the local project, the proxy class has implemented the code of asynchronous calls. public class Form2: System.Windows.Forms.Form {private localhost.StockPrice m_stockService; private IAsyncResult m_handle; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.TextBox messageBox; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button6; ///
Public Form2 () {// // Windows Form Designer Support for // InitializationComponent ();
// // Todo: Add any constructor code after INITIALIZEComponent call //}
///
#REGION Windows Form Designer The code ///
/// summary> private void InitializeComponent () {this.messageBox = new System.Windows.Forms.TextBox (); this.button1 = new System.Windows.Forms.Button (); this.button2 = new System. Windows.Forms.Button (); this.button3 = new system.windows.forms.button (); this.button4 = new system.windows.Forms.Button (); this.button5 = new System.Windows.Forms.Button (); This.button6 = new system.windows.Forms.Button (); this.suspendlayout (); // // messagebox // this.MessageBox.location = new system.drawing.point (16, 8); this .messageBox.Multiline = true; this.messageBox.Name = "messageBox"; this.messageBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.messageBox.Size = new System.Drawing.Size (656, 320) This.MessageBox.TabINDEX = 0; this.MessageBox.text = ""; /// Button1 // this.button1.location = new system.drawing.point (24, 344); this.button1.name = " Button1 "; this.button1.tabindex = 1; this.button1.text =" call "; this.button1.clic K = new system.eventhandler (this.button1_click); // // button2 // this.button2.location = new system.drawing.point (128, 344); this.button2.name = "button2"; this. Button2.tabindex = 2; this.button2.text = "polling"; this.button2.click = new system.eventhandler (this.button2_click); // // button3 // this.button3.location = new system. Drawing.Point (240, 344); this.button3.name = "button3"; this.button3.tabindex = 3; this.button3.text = "abort"; this.button3.click = new system.EventHandler (this .button3_click;
// // button4 // this.button4.location = new system.drawing.point (352, 344); this.button4.name = "button4"; this.button4.size = new system.drawing.size (96, 23); this.button4.tabindex = 4; this.button4.text = "Wait for asynchronous operation"; this.button4.click = new system.eventhandler (this.button4_click); // // Button5 // this.button5 .Location = new system.drawing.point (464, 344); this.button5.name = "button5"; this.button5.size = new system.drawing.size (120, 23); this.button5.tabindex = 5 "This.button5.text =" Three services once again "; this.button5.click = new system.eventhandler (this.button5_click); // // button6 // this.button6.location = new system.drawing. Point (608, 344); this.button6.name = "button6"; this.button6.tabindex = 6; this.button6.text = "Tune processing"; this.button6.click = new system.EventHandler (this. Button6_click; // // Form2 // this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (696, 477); th Is.Controls.add (this.button6); this.controls.add (this.button5); this.controls.add (this.button4); this.controls.add (this.button3); this.controls.add ( this.button2); this.controls.add (this.button1); this.controls.add (this.MessageBox); this.name = "form2"; this.text = "form2"; this.Load = new system . Eventhandler (this.form2_load); this.ResumeLayout (false);} #ENDREGION
Private Void Form2_Load (Object Sender, System.EventArgs E) {}
// You call BeGingeTStockPrice () to get an object with an IASYNCRESULT interface. // It provides an ISCOMPLETED attribute. When this value is "true", // You can get the result of the function run by calling endgetStockPrice (). // More importantly, you can "abandon the Abort" call when asynchronous calls. // The following program segment is to use three "buttton" to indicate how to use asynchronous calls, check whether the call is ended and the call. // asynchronous call WebMethod private void button1_Click (object sender, System.EventArgs e) {m_stockService = new localhost.StockPrice (); m_handle = m_stockService.BegingetStockPrice ( "IBM", null, null); messageBox.Text = "is invoked Web service. " System.environment.newline;
} // Check if the asynchronous call is completed. If you are finished, remove the call result private void button2_click (object sender, system.eventargs e) {if (m_handle == null) {messagebox.text = "No service is called!" System.environment.newline; return; } if (m_handle.IsCompleted == false) messageBox.Text = "service is call" System.Environment.NewLine; else {double price = m_stockService.EndgetStockPrice (m_handle); messageBox.Text = "amount:" Price system.environment.newline;}
}
// asynchronous calls abandoned private void button3_Click (object sender, System.EventArgs e) {if (m_handle = null!) {WebClientAsyncResult result = (WebClientAsyncResult) m_handle; result.Abort (); m_handle = null;} messageBox.Text = "Call service is terminated by the user" system.environment.newline;
}
// Get an object with an IASYNCRESULT interface after calling BegingeTStockPrice (). // It provides the properties of AsyncWaithandle. The waitone () function calling it allows the program to be blocked until another thread function call is completed. // The program will continue to be executed down. private void button4_Click (object sender, System.EventArgs e) {if (this.m_stockService == null) m_stockService = new localhost.StockPrice (); m_handle = m_stockService.BegingetStockPrice ( "IBM", null, null); messageBox.Text = "is calling the service" System.Environment.NewLine; m_handle.AsyncWaitHandle.WaitOne (); double price = m_stockService.EndgetStockPrice (m_handle); messageBox.Text = "amounting to:" price System.Environment.NewLine; }
// From the phenomenon, and the synchronous calls have not been benefited. The program is still in the "hanging" state when waiting. / / However, in some cases, "Waiting" still has its characteristics. // For example, you can call three WebMethod continuously, if each function is 5 seconds, //, then use synchronization, for 15 seconds. But if you use asynchronous, you may wait for 5 seconds. // Of course this is to use the waitLL () function provided by WaitHandle. As follows: @ a service call to three private void button5_Click (object sender, System.EventArgs e) {if (this.m_stockService == null) m_stockService = new localhost.StockPrice (); IAsyncResult [] handles = new IAsyncResult [ 3]; MessageBox.Text = "One call three services: start time" DateTime.now.tostring () system.environment.Newline; handles [0] = m_stockService.BegingeTStockPrice ("IBM", NULL, NULL ); handles [1] = m_stockService.BegingetStockPrice1 ( "MS", null, null); handles [2] = m_stockService.BegingetStockPrice2 ( "SUN", null, null); WaitHandle [] WaitHandles = {handles [0] .AsyncWaitHandle Handles [1] .asyncWaithandle, Handles [2] .asyncwaithandle}; // The function is blocked until 3 functions are executed. Waitany () function is similar, but there is a function to complete // proactive, continue to execute WaitHandle.Waitall (WaitHandles); MessageBox.Text = "call completion time is:" DateTime.now.tostring () System.environment.newline; double [] price = new double [3]; for (int i = 0; i <3; i ) {prices [i] = m_stockservice.endgetstockprice (Handles [i]); messagebox.text = "The amount is:" prices [i] system.environment.newline;} messagebox.text = "call three services complete:" system.environment.newline;}
// See now, you may not be satisfied yet. Because you call the function asynchronously, you have to manually check if the function is executed, // or you want to wait. Can you make the function after the function is complete, or do other operations? // The answer is "energy". The callback function is to do this. private void button6_Click (object sender, System.EventArgs e) {if (this.m_stockService == null) m_stockService = new localhost.StockPrice (); // generates a callback AsyncCallback cb = new AsyncCallback (this.callback); m_stockService.BegingetStockPrice ( "IBM", cb, DateTime.Now); messageBox.Text = "remote service is called" System.Environment.NewLine;} private void callback (IAsyncResult handle) {double price = m_stockService.EndgetStockPrice (handle); lock (this) {MessageBox.Text = "The amount is:" Price ". Request time:" " " ", end time:" DateTime.now.tostring () system.environment .Newline;}}}}}}