.NET 1.x 非同步呼叫需使用 BeginXX/EndXX 配合 AsyncCallback 與 IAsyncResult,程式碼繁瑣。.NET 2.0 (VS 2005) 引入事件基礎非同步模式,大幅簡化客戶端程式碼。
void DoSomethingTest() {
localhost.Service service = new WindowsApp.localhost.Service();
service.HelloWorldCompleted += new WindowsApp.localhost.HelloWorldCompletedEventHandler(service_HelloWorldCompleted);
service.HelloWorldAsync(); // 發起非同步呼叫
}
void service_HelloWorldCompleted(object sender, WindowsApp.localhost.HelloWorldCompletedEventArgs e) {
if (e.Error == null) {
MessageBox.Show(e.Result); // 強型別回傳值
} else {
MessageBox.Show(e.Error.Message);
}
}
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService {
[WebMethod]
public string HelloWorld() { return "Hello World"; }
}
AsyncCallback、IAsyncResult 兩大痛點e.Result 取得 ("Hello World")e.Error有興趣可檢視 VS 2005 產生的 Reference.cs,比 2003 版複雜許多,內含:
System.ComponentModel.AsyncCompletedEventArgsSystem.Threading.SendOrPostCallback (delegate)這些類別不僅用於 Web Service 客戶端,更是 .NET 2.0 非同步程式設計基礎設施的核心組件。