C#不同方式调用webservice

继上一篇不添加引用调用webservice这次我们谈谈添加引用调用webservice的几种方式。

首先我们可以看到添加webservice引用有2种,如图:

C#不同方式调用webservice_第1张图片一种叫service References,另一种叫Web Reference(.net framework 3.5或以下才有)

现在我们就来看看分别在这两种引用下调用webservice。

1、Service References下的同步调用:

        /// 
        /// Service References引用下同步获取数据
        /// 
        protected void GetUserInfo()
        {
            //CheckEmpEmail
            LoginService.LoginSoapClient client = new LoginService.LoginSoapClient();
            this.Label1.Text = client.GetUserInfo("[email protected]");
        }


2、Service References下使用backgroundworker异步请求数据

        /// 
        /// Service References下使用backgroundworker的方式使同步方法异步化
        /// 
        protected void GetUserInfo()
        {
            BackgroundWorker backgroundworker = new BackgroundWorker();
            backgroundworker.DoWork += new DoWorkEventHandler(backgroundworker_DoWork);
            backgroundworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundworker_RunWorkerCompleted);
            backgroundworker.RunWorkerAsync("[email protected]");
        }

        protected void backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Label1.Text = e.Result.ToString();
        }

        protected void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
        {
            LoginService.LoginSoapClient client = new LoginService.LoginSoapClient();
            e.Result = client.GetUserInfo(e.Argument.ToString());
        }

3、在Web Reference引用下异步获取数据

        /// 
        /// 用webservice异步获取数据
        /// 必须使用WebReference的形式来添加webservice引用
        /// 
        protected void GetUserInfo()
        {
            WebReference.Login loginService = new WebReference.Login();
            loginService.GetUserInfoCompleted += new WebReference.GetUserInfoCompletedEventHandler(l_GetUserInfoCompleted);
            loginService.GetUserInfoAsync("[email protected]");
        }

        protected void l_GetUserInfoCompleted(object sender, WebReference.GetUserInfoCompletedEventArgs e)
        {
            this.Label1.Text = e.Result;
        }


你可能感兴趣的:(asp.net,c#)