如何限制特定类可以分配的内存?
我在运行时将多个外部程序集加载到我的应用程序中。我需要限制每个外部程序集中定义的特定类可以使用的内存量,例如每个实例 10 mb,否则我们会出现 OutOfMemory。
我在 google 上搜索了执行此操作的最佳方法,并找到了一些有关 CLR 运行时的信息托管。这似乎是我需要的东西,但我找不到任何好的例子。
任何人都可以分享代码示例或一些有关使用 CLR 运行时托管进行内存管理的链接吗? 或者也许有一些更好的解决方案来限制每个类的内存量?
提前致谢。
I'm loading several external assemblies into my application at runtime. And I need to limit an amount of memory that can be used by a specific class which is defined in each of the external assemblies, for example, 10 mb per instance, otherwise we get OutOfMemory.
I've googled what is the best way to do this and found some information about CLR Runtime Hosting. It seems to be the thing I need, but I can not find any good examples.
Can anyone share the examples of code or maybe some links about memory management using CLR Runtime Hosting?
Or maybe there are some better solutions to limit an amount of memory per class?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是您可以通过 CLR 托管完成的事情。如果您托管 CLR,则可以满足从 GC 到 Windows 的分配要求,例如,它可以使用其他分配器来代替 VirtualAlloc。但是,每次分配对象时都不会调用主机(这太昂贵了)。
理论上,您可以使用 CLR Profiling API 来完成此任务。它确实允许您在分配对象时接收回调。
但我担心你试图从错误的角度看待这个问题。您是否可以尝试将这些外部程序集隔离到单独的进程中,甚至可能使用 Win32 作业对象 API 来限制它们,而不是限制类实例使用的内存量(这是非常精细的)?
This is not something you will be able to do through CLR Hosting. If you host the CLR, you can fulfill allocation requirements from the GC to Windows, e.g. so that instead of VirtualAlloc it uses some other allocator. However, the host is not invoked every time an object is allocated (this would be too expensive).
You could theoretically accomplish this by using the CLR Profiling API. It does allow you to receive a callback whenever an object is allocated.
I'm afraid, though, that you're trying to look at this from the wrong perspective. Instead of limiting the amount of memory used by instances of a class, which is very granular, could you instead try and isolate these external assemblies into separate processes, possibly even limiting them using the Win32 Job Object APIs?
如果您的目标是限制单个进程的内存消耗,我认为您应该使用 Process 类的“MaxWorkingSet”属性。请参阅 http://msdn.microsoft.com/en- us/library/system.diagnostics.process.maxworkingset.aspx 了解详细信息
If you aim is limitate individual process memory consumtion, I think you shold use 'MaxWorkingSet' property of Process class. See http://msdn.microsoft.com/en-us/library/system.diagnostics.process.maxworkingset.aspx for details