通过对接口调用可能出现的异常作出判断和处理,避免资源的浪费和占用~
1 public class SvcHelper 2 { 3 public static void Using(T client, Action action) where T : ICommunicationObject 4 { 5 try 6 { 7 action(client); 8 client.Close(); 9 } 10 catch (CommunicationException) 11 { 12 client.Abort(); 13 throw; 14 } 15 catch (TimeoutException) 16 { 17 client.Abort(); 18 throw; 19 } 20 catch (Exception) 21 { 22 client.Abort(); 23 throw; 24 } 25 } 26 }
调用方法
var T = new XXX(); SvcHelper.Using(client => { T = client.SomeMethod(); } return T;