WCF异步

WCF异步与否由客户端来决定

服务端接口:

// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        string SayHello(string name);
    }

 // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }


        public string SayHello(string name)
        {
            System.Threading.Thread.Sleep(5000);
            return "hello" + name;
        }
    }

前台生成同步+异步方法

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WCF.Syn.Serivces.Service1Client _client = new WCF.Syn.Serivces.Service1Client();
            MessageBox.Show(_client.SayHello("peter.peng"));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            WCF.Syn.Serivces.Service1Client _client = new WCF.Syn.Serivces.Service1Client();
            _client.SayHelloCompleted+= new EventHandler<WCF.Syn.Serivces.SayHelloCompletedEventArgs>(_client_GetDataCompleted);//第一种方式
            _client.SayHelloAsync("peter");//第一种方式

            //_client.BeginSayHello("peter.peng", doCallBack, _client);//第二种方式
        }

        void _client_GetDataCompleted(object sender, WCF.Syn.Serivces.SayHelloCompletedEventArgs e)//第一种方式
        {
            MessageBox.Show(e.Result);
        }
        private void doCallBack(IAsyncResult result)
        {
            //string s = ((WCF.Syn.Serivces.Service1Client)result.AsyncState).EndSayHello(result);//第二种方式
            //MessageBox.Show(s);//第二种方式
        }
    }

原文地址:https://www.cnblogs.com/peter-peng/p/3452818.html