问题描述
我应该在不再使用非全局ConcurrentDictionary时明确地清除它,还是GC检测到它不再使用了?
这与以下内容有关:Is ConcurrentBag cause of memory leak?
编辑: 我问的原因是,我有以下类型的代码(在此处简化):
let myMethod() =
async {
let myEventList = ConcurrentDictionary<myEventParams,bool>()
use o = myEvent |> Observable.subscribe(fun e ->
myEventList.GetOrAdd(e,true) |> ignore)
let! res = doAsyncThingsCausingEvents()
myEventList |> Seq.iter(fun (e,_) -> Console.WriteLine "We had " + e.ToString())
res
}
...实际上,当在多个线程中多次并行调用时,它会泄漏内存。
解决方法
有趣的问题。 ConcurrentDictionary
不是IDisposable
,所以我希望它像其他任何对象一样工作。即,当不再引用它时,它就有资格进行收集,包括没有其他引用的所有自有物品。
通过分配ConcurrentDictionary,使引用为空并捕获内存快照进行快速测试表明确实如此。