体验.net 2.0 的优雅(1) -- 异步WebService调用

    
   在.net1.x中,异步WebService异步调用的一般方式为调用方法XX对应的BeginXX方法来完成,其过程类似于异步委托的使用。详情请点此了解。

    在.net2.0中(准确的说是vs 2005中),异步WebService异步调用的方式的例子:



void DoSomethingTest()
        
{
            localhost.Service service 
= new WindowsApp.localhost.Service();

            service.HelloWorldCompleted 
+= new WindowsApp.localhost.HelloWorldCompletedEventHandler(service_HelloWorldCompleted);
            
// do Asyn calling here
            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);
            }

        }

服务器端代码



        很简单,没有了AsyncCallback、IAsyncResult 这两个烦人的东西,调用的代码变得简洁、优雅了,而且可以从e.Result得到强类型的返回值(上例为"Hello World")。但是,有兴趣的话,可以看看vs 2005生成的Referance.cs文件,那可比2003中的复杂很多。其中可以看到System.ComponentModel.AsyncCompletedEventArgs 、 System.Threading.SendOrPostCallback(delegate)这两个在 .net 1.x 中没有的“怪物”,估计用到的地方还不止WebService客户端。有时间再研究看看。



posted @ 2005-11-13 01:27  quitgame  阅读(6254)  评论(17编辑  收藏  举报