Wcf异步调用简单示例

WCF异步调用重要的一点就是跟服务契约毫无关系,异步或者非异步都是客户端说了算.所以要想让客户端异步调用服务,如何配置客户端是重点了,下面我来介绍:

1.首先是一个简单的服务契约定义

View Code
//在这里我故意使用非会话服务,也就是说异步不异步跟会话没关系
[ServiceContract(SessionMode= SessionMode.NotAllowed)]
    interface IWcfService
    {
        [OperationContract]
        string SayHello(string name);
    }

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    class WcfService:IWcfService
    {
        public string SayHello(string name)
        {
            Console.WriteLine(name+ " is connected");
            return "Welcome! "+name;
        }
    }

2.客户端引入服务定义,我在这里使用VS的自动导入功能,并勾选自动生成异步操作

在客户端的服务定义里会自动生成异步的BeginSayHello和EndSayHello方法

View Code
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="WcfService.IWcfService", SessionMode=System.ServiceModel.SessionMode.NotAllowed)]
    public interface IWcfService {
        
        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IWcfService/SayHello", ReplyAction="http://tempuri.org/IWcfService/SayHelloResponse")]
        string SayHello(string name);
        
        [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/IWcfService/SayHello", ReplyAction="http://tempuri.org/IWcfService/SayHelloResponse")]
        System.IAsyncResult BeginSayHello(string name, System.AsyncCallback callback, object asyncState);
        
        string EndSayHello(System.IAsyncResult result);
    }

因此客户端调用服务的时候可以用同步也可以用异步,想咋的就咋的.但是要注意一下微软异步编程模型(APM)的使用方法:

View Code
WcfServiceClient proxy = new WcfServiceClient();
            string info = proxy.SayHello("HarleyHu"); //同步
            Console.WriteLine(info);

            proxy.BeginSayHello("HuWen",
            ia=>{
                info = ((WcfServiceClient)ia.AsyncState).EndSayHello(ia); //异步
                Console.WriteLine(info);
            },
            proxy);
            Console.Read();

今天就到这了

 

posted @ 2012-12-06 16:34  Harley Hu  阅读(1333)  评论(4编辑  收藏  举报