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

查看:30
本文介绍了如何使用 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天全站免登陆