WCF技术剖析之十:调用WCF服务的客户端应该如何进行异常处理2012-10-17 博客园 Artech在前面一片文章(服务代理不能得到及时关闭会有什么后果?)中,我们谈到及时关闭服务代理(Service Proxy)在一个高并发环境下的重要意义,并阐明了其根本原因。但是,是否直接调用ICommunicationObject的Close方法将服务代理关闭就万事大吉了呢?事情远不会这么简单,这其中还会涉及关于异常处理的一些操作,这就是本篇文章需要讨论的话题。一、异常的抛出与Close的失败一般情况下,当服务端抛出异常,客户客户端的服务代理不能直接关闭,WCF在执行Close方法的过程中会抛出异常。我们可以通过下面的例子来证实这一点。在这个例子中,我们依然沿用计算服务的例子,下面是服务契约和服务实现的定义:
1: using System.ServiceModel;
2: namespace Artech.ExceptionHandlingDemo.Contracts
3: {
4: [ServiceContract(Namespace = "urn:artech.com")]
5: public interface ICalculator
6: {
7: [OperationContract]
8: int Divide(int x, int y);
9: }
10: }
1: using System;
2: using System.ServiceModel;
3: using Artech.ExceptionHandlingDemo.Contracts;
4: namespace Artech.ExceptionHandlingDemo.Services
5: {
6: class CalcualtorService : ICalculator { public int Divide(int x, int y) { return x / y; } }
7: }
为了确保服务代理的及时关闭,按照典型的编程方式,我们需要采用try/catch/finally的方式才操作服务代理对象,并把服务代理的关闭放在finally块中。WCF服务在客户端的调用程序如下所示:
1: using System;
2: using System.ServiceModel;
3: using Artech.ExceptionHandlingDemo.Contracts;
4: namespace Client
5: {
6: class Program
7: {
8: static void Main(string[] args)
9: {
10: using (ChannelFactory<ICalculator> channelFatory = new ChannelFactory<ICalculator>(new WSHttpBinding(), "http://127.0.0.1:3721/calculatorservice"))
11: {
12: ICalculator calcultor = channelFatory.CreateChannel(); try
13: {
14: calcultor.Divide(1, 0);
15: }
16: catch (Exception ex) { Console.WriteLine(ex.Message); }
17: finally
18: {
19: (calcultor as ICommunicationObject).Close();
20: }
21: }
22: }
23: }
24: }
由于传入的参数为1和0,在服务执行除法运算的时候,会抛出DividedByZero的异常。当服务端程序执行到finally块中对服务代理进行关闭的时候,会抛出如下一个CommunicationObjectFaultedException异常,提示SerivceChannel的状态为Faulted,不能用于后续Communication。