WebService服务的异步调用

       在winfrom程序中,我们往往需要通过异步操作进行后台某些运算或者服务调用。今天记录一下在winfrom程序下异步调用webservice服务的方法

异步有返回值方法1: 

       private async Task<string> PostAsync(string json)
        {
            var resut = await Task.Run(() =>
            {
                ServiceReference1.WebService1SoapClient webService1 = new ServiceReference1.WebService1SoapClient();
                string s = webService1.Add(json);
                System.Threading.Thread.Sleep(10000);
                return s;
            });
            return resut;          

        }

异步有返回值方法2:

private async Task<string> Post(string json)
        {
          var resut=await  Task.Run(() =>
            {
                ServiceReference1.WebService1SoapClient webService1 = new ServiceReference1.WebService1SoapClient();
                string s = webService1.Add(json);
                System.Threading.Thread.Sleep(10000);
                return s;
            });          

            return  await Task.FromResult(resut);          

        }


都是异步有返回值方法,区别在于:Task.FromResult

winfrom中调用

 private async void button1_Click(object sender, EventArgs e)
        {
          var sting= await PostAsync("sss");
            label1.Text = sting;
        }

例子

  async Task<int> GetAddAsync(int x,int y)
        {
            //Task.FromResult 是一个占位符,类型为 DateTime
            return await Task.FromResult(x+y);
        }

 

posted @ 2022-07-30 11:24  眯眼看世界  阅读(509)  评论(0编辑  收藏  举报