请教一下 ChannelFactory<T>.CreateChannel() 创建出来的怎么能安全,方便的释放资源?
目前我是做了一个封装,然后:using(var client = new Client<IMyService>())
{
//调用}这样来释放,但总感觉使用 using 很累也不好看.请问 ChannelFactory<T>.CreateChannel() 创建出来的需要保证释放一定要释放掉吗?有没有更方便有效的办法?下面是Client代理类的大致方法:public class Client<T> : IDisposable
{
private readonly T client; public Client()
{
var factory = new ChannelFactory<T>();
client = factory.CreateChannel();
}
public void Dispose()
{
if (disposed) return; try
{
var c = client as ICommunicationObject;
if (c != null)
{
CloseConnection(c);
}
}
catch (Exception ex)
{
Debug.WriteLine("Client dispose error:" + ex.Message);
} disposed = true;
}
public static void CloseConnection(ICommunicationObject myServiceClient)
{
if (myServiceClient.State != CommunicationState.Opened)
{
return;
}
try
{
myServiceClient.Close();
}
catch (CommunicationException ex)
{
myServiceClient.Abort();
}
catch (TimeoutException ex)
{
myServiceClient.Abort();
}
catch (Exception ex)
{
myServiceClient.Abort();
throw;
}
}
}
目前我是做了一个封装,然后:using(var client = new Client<IMyService>())
{
//调用}这样来释放,但总感觉使用 using 很累也不好看.请问 ChannelFactory<T>.CreateChannel() 创建出来的需要保证释放一定要释放掉吗?有没有更方便有效的办法?下面是Client代理类的大致方法:public class Client<T> : IDisposable
{
private readonly T client; public Client()
{
var factory = new ChannelFactory<T>();
client = factory.CreateChannel();
}
public void Dispose()
{
if (disposed) return; try
{
var c = client as ICommunicationObject;
if (c != null)
{
CloseConnection(c);
}
}
catch (Exception ex)
{
Debug.WriteLine("Client dispose error:" + ex.Message);
} disposed = true;
}
public static void CloseConnection(ICommunicationObject myServiceClient)
{
if (myServiceClient.State != CommunicationState.Opened)
{
return;
}
try
{
myServiceClient.Close();
}
catch (CommunicationException ex)
{
myServiceClient.Abort();
}
catch (TimeoutException ex)
{
myServiceClient.Abort();
}
catch (Exception ex)
{
myServiceClient.Abort();
throw;
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货