如何避免使用LINQ-to-SQL的内存泄漏? [英] How do I avoid a memory leak with LINQ-To-SQL?

查看:442
本文介绍了如何避免使用LINQ-to-SQL的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用LINQ-to-SQL时遇到了一些问题。我在Windows服务中使用它来做一些处理,我正在循环通过大量的数据,我从上下文中拉回。是的 - 我知道我可以用一个存储过程,但有理由为什么这将是一个不太理想的解决方案。

I have been having some issues with LINQ-To-SQL around memory usage. I'm using it in a Windows Service to do some processing, and I'm looping through a large amount of data that I'm pulling back from the context. Yes - I know I could do this with a stored procedure but there are reasons why that would be a less than ideal solution.

无论如何,我看到的基本上是内存即使调用 context.SubmitChanges()后也不会释放。所以我最终不得不做各种奇怪的事情,如只提取100条记录在时间,或创建几个上下文,并让他们都做单独的任务。如果我保持相同的 DataContext 并且使用它以后为其他调用,它只是吃了越来越多的内存。即使我在查询返回给我的 var tableRows 数组上调用 Clear(),将其设置为null,并调用 SYstem.GC.Collect() - 它仍然不释放内存。

Anyway, what I see basically is memory is not being released even after I call context.SubmitChanges(). So I end up having to do all sorts of weird things like only pull back 100 records at time, or create several contexts and have them all do separate tasks. If I keep the same DataContext and use it later for other calls, it just eats up more and more memory. Even if I call Clear() on the "var tableRows" array that the query returns to me, set it to null, and call SYstem.GC.Collect() - it still doesn't release the memory.

我已经阅读了一些关于你应该如何使用 DataContexts 并快速处理它们,但似乎他们应该是一种强制上下文转储其所有数据的方式

Now I've read some about how you should use DataContexts quickly and dispose of them quickly, but it seems like their ought to be a way to force the context to dump all its data (or all its tracking data for a particular table) at a certain point to guarantee the memory is free.

任何人知道什么步骤保证内存被释放?

Anyone know what steps guarantee that the memory is released?

推荐答案

如果您不需要对象跟踪,请将 DataContext.ObjectTrackingEnabled 设置为 false 。如果你确实需要它,你可以使用反射来调用内部 DataContext.ClearCache(),虽然你必须意识到,自从它的内部,它将在框架的未来版本中消失。就我可以告诉,框架本身不使用它,但它清除对象缓存。

If you don't need object tracking set DataContext.ObjectTrackingEnabled to false. If you do need it, you can use reflection to call the internal DataContext.ClearCache(), although you have to be aware that since its internal, it's subject to disappear in a future version of the framework. And as far as I can tell, the framework itself doesn't use it but it does clear the object cache.

这篇关于如何避免使用LINQ-to-SQL的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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