WCF 异步操作

3778人阅读 2021/4/25 9:51 总访问:652318 评论:0 收藏:0 手机
分类: .net

  前  言

tnblog

代码从上往下执行,代码没执行完不能进行其他的操作,这个时候就需要使用异步避免这个坑(功能类似于Ajax)

Service2 中存在一个乘积的方法,但是要等待两秒后才能执行(模拟代码比较多的时候,运行时间较长)

 //wcf中的方法
  public int Cheng(int a,int b)
        {
            System.Threading.Thread.Sleep(2000);
            return a * b;
        }

异步请求方法一 (开辟线程)

            //命名空间
            using System.Threading;
            //方法一Thread
            Thread thread = new Thread(() =>
            {
               //实例化方法
                Service2.Service2Client client = new Service2.Service2Client();
                
                string str = client.Cheng(2, 3).ToString();
                MessageBox.Show(str);
            });
            //启动Thread 
            thread.Start();
            
            
            //命名空间
            using System.Threading.Tasks;
            //方法二Task
            Task.Run(() =>
            {
                Service2.Service2Client client = new Service2.Service2Client();
                string str = client.Cheng(2, 3).ToString();
                MessageBox.Show(str);
            });

异步请求方法二 (async,await)               调用异步方法(方法名Async)

        //方法二async,await
        //重新创建一个异步的方法,需要用的时候直接调方法就可以了
        public async void ClientCheng() 
        {
            Service2.Service2Client client = new Service2.Service2Client();
            int num = await client.ChengAsync(2,3);
            MessageBox.Show(num.ToString());
        }

异步请求方法三 (Wcf自带的异步)         

第一步:


第二步:

代码部分

            //Wcf自带的异步
            Service2.Service2Client client = new Service2.Service2Client();
            //调用异步方法(方法名Async)
            client.ChengAsync(5, 6);
            //方法名+Completed 事件
            client.ChengCompleted += client_ChengCompleted; 
            
            
             
            //生成的事件
              void client_ChengCompleted(object sender, Service2.ChengCompletedEventArgs e)
                {
                //e.Result代表方法的返回值
                
                    MessageBox.Show("乘积是:" + e.Result);
                }


评价
脚踏实地,一步一个脚印
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术