ConcurrentQueue的内存泄漏 [英] Memory leak with ConcurrentQueue

查看:464
本文介绍了ConcurrentQueue的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ConcurrentQueue时,我发生内存泄漏:

i have memory leak when using ConcurrentQueue :

requestObject request = xxx;

Item obj= new Item ();
obj.MessageReceived += obj_MessageReceived;
obj.Exited += obj_Exited;

request.Key = obj.Key;

obj.AddRequest(request);

_queue.TryAdd(obj.Key, obj);

在退出"回调中,我配置资源:

In the "Exited" callback, i dispose the resource :

void LiveSphere_Exited(string key)
{
    Item instance;

    _queue.TryRemove(key, out instance);

    Task.Factory.StartNew(() =>
    {
        var wait = new SpinWait();
        while (instance.MessageCount > 0)
        {
            wait.SpinOnce();
        }
    })
    .ContinueWith((t) =>
    {
         if (instance != null)
         {
             //Cleanup resources
             instance.MessageReceived -= obj_MessageReceived;
             instance.Exited -= obj_Exited;
             instance.Dispose();
             instance = null;
         }
    });
}

当我分析代码时,我仍然有一个根目录引用了"Item"对象,但是我不知道该在哪里放置..., 触发退出的方法,并且_queue从队列中删除了"Item"对象.

When I profile the code, i still have a root referenced "Item" object but I don't know where I can dispose..., The exited method is triggered and the _queue has removed the "Item" object from the queue.

当我阅读文档时,并发队列会将引用复制到队列中.

When I read documentation, the concurrentqueue copy the reference into the queue.

您能帮我找出内存泄漏在哪里吗?

Can you help me to find out where the memory leak is?

推荐答案

与标准.NET队列不同,调用Dequeue()不会从集合中删除对该对象的引用.尽管此行为已从4.0版本更改为4.5版本(我已经阅读过但未测试),但这不是错误,而是框架团队在设计线程安全时做出的有意识的设计决策. ,可枚举的集合.

Unlike a standard .NET Queue, calling Dequeue() does not remove the reference to the object from the collection. While this behavior has changed from the 4.0 version to the 4.5 version (I have read this, but have not tested it) it is not a bug, but a conscious design decision made by the framework team as a part of designing a thread-safe, enumerable collection.

This article has more information, including a workaround by using StrongBox to wrap the objects that go into the ConcurrentQueue. That should be a suitable work-around until you can move to the 4.5 framework.

这篇关于ConcurrentQueue的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆