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

体验.net 2.0 的优雅 -- 异步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);
            }
        }
服务器端代码 

[WebService(Namespace = "
http://tempuri.org/
")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {
    } 
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }


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

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [Visual Studio.NET] 的这些文章也感兴趣:

LCS使用RTC API 发送IM消息的WebService
Visual Studio 2008 SDK Version 1.0
.NET Create Excel 2007 file with open xml
.NET产生动态程序集
Mono的WinForms 2.0的代码已经完成
VS2008 椭圆曲线签名(ECDSA)
ObjectBuilder中WeakRefDictionary使用模式浅析
VSTS 离线源码版本辅助工具
微软同步框架(MSF)入门开篇(附SnapShot快照Demo)
Windows PowerShell 使用方法总结