【发布时间】:2012-05-24 22:36:47
【问题描述】:
目前我缓存ServiceChannelFactory 并在每次需要时创建一个新的ServiceChannel。我希望垃圾收集器处理ServiceChannels。但是,工厂保留了对每个通道的引用,以便在您调用ServiceFactoryChannel.Close() 时可以关闭通道。这会导致许多旧频道一直处于活动状态,直到一切都停止工作。
如何在缓存工厂的同时让垃圾收集器处理我的频道?
我的代码如下所示:
public class ServiceChannel
{
// Returns a ServiceChannel
public static TService Get<TService>()
{
var factory = GetChannelFactory<TService>();
string url = GetEndpoint<TService>();
var endPoint = new EndpointAddress(url);
return factory.CreateChannel(endPoint);
}
// Returns a ServiceChannelFactory, preferably from the cache
public static ChannelFactory<TService> GetChannelFactory<TService>()
{
var cacheKey = string.Format("MyProduct.Library.ServiceChannel.GetChannelFactory<{0}>()", typeof(TService));
var cache = HttpRuntime.Cache;
var factory = cache[cacheKey] as ChannelFactory<TService>;
if (factory == null)
{
factory = GetChannelFactoryUncached<TService>();
cache.Insert(cacheKey, factory);
}
return factory;
}
}
【问题讨论】:
-
您能否详细说明一切都停止工作?您应该分享您正在缓存的方式(代码很有帮助),例如你在使用滑动过期、内存缓存等吗?
-
我一直在创建频道。每个通道都保持一个输出端口打开,所以一段时间后这些都用完了。结果是服务器无法再建立新的 TCP 连接。