在项目中采用wcf通讯,客户端很多地方调用服务,需要统一的处理超时和通讯异常以及关闭连接。
1.调用尝试和异常捕获
首先,项目中添加一个通用类ServiceDelegate.cs
1 public delegate void UseServiceDelegate<T>(T proxy); 2 3 public static class Service<T> 4 { 5 public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>(""); 6 7 public static void Use(UseServiceDelegate<T> codeBlock) 8 { 9 T proxy = _channelFactory.CreateChannel(); 10 bool success = false; 11 12 13 Exception mostRecentEx = null; 14 for(int i=0; i<5; i++) // Attempt a maximum of 5 times 15 { 16 try 17 { 18 codeBlock(proxy); 19 proxy.Close(); 20 success = true; 21 break; 22 } 23 24 // The following is typically thrown on the client when a channel is terminated due to the server closing the connection. 25 catch (ChannelTerminatedException cte) 26 { 27 mostRecentEx = cte; 28 proxy.Abort(); 29 // delay (backoff) and retry 30 Thread.Sleep(1000 * (i + 1)); 31 } 32 33 // The following is thrown when a remote endpoint could not be found or reached. The endpoint may not be found or 34 // reachable because the remote endpoint is down, the remote endpoint is unreachable, or because the remote network is unreachable. 35 catch (EndpointNotFoundException enfe) 36 { 37 mostRecentEx = enfe; 38 proxy.Abort(); 39 // delay (backoff) and retry 40 Thread.Sleep(1000 * (i + 1)); 41 } 42 43 // The following exception that is thrown when a server is too busy to accept a message. 44 catch (ServerTooBusyException stbe) 45 { 46 mostRecentEx = stbe; 47 proxy.Abort(); 48 49 // delay (backoff) and retry 50 Thread.Sleep(1000 * (i + 1)); 51 } 52 53 catch(Exception ) 54 { 55 // rethrow any other exception not defined here 56 // You may want to define a custom Exception class to pass information such as failure count, and failure type 57 proxy.Abort(); 58 throw ; 59 } 60 } 61 if (mostRecentEx != null) 62 { 63 proxy.Abort(); 64 throw new Exception("WCF call failed after 5 retries.", mostRecentEx ); 65 } 66 67 } 68 }