C#中的内存使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/755919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Memory usage in C#
提问by yoitsfrancis
I have a program that uses threads in C#. Is there a way to know programmatically the memory usage of the application? I want to limit the spawning of threads to say 10 megabytes of memory, how would I do that?
我有一个在 C# 中使用线程的程序。有没有办法以编程方式了解应用程序的内存使用情况?我想将线程的产生限制为 10 兆字节的内存,我该怎么做?
采纳答案by binarybob
If you want the memory of the entire running process and not on a per thread basis, how about:
如果您想要整个运行进程的内存而不是每个线程的内存,那么如何:
// get the current process
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
// get the physical mem usage
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
There's a whole host of other process memory properties besides WorkingSet64
check out the "memory related" ones at the following link for the one that best suit
除了WorkingSet64
在以下链接中查看“与内存相关”的属性之外,还有许多其他进程内存属性最适合的
http://msdn.microsoft.com/en-us/library/system.diagnostics.process_properties.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.process_properties.aspx
回答by Binary Worrier
I'm with Will and Steve, don't do this unless you REALLY have to do it . . . that said . . .
我和威尔和史蒂夫在一起,除非你真的必须这样做,否则不要这样做。. . 那说。. .
if you really need to do it you can use the .Net Hosting APIsthey're there so apps like SQL Server can host the .net framework within the application.
如果你真的需要这样做,你可以使用 .Net Hosting APIs,它们在那里,所以像 SQL Server 这样的应用程序可以在应用程序中托管 .net 框架。
It gives you control over memory management etc, I've read the article but never used the API's, they're on my to-do list for some night when I'm bored and none of my other "fun" projects feel like fun that week :)
它让您可以控制内存管理等,我读过这篇文章但从未使用过 API,当我无聊时,它们会出现在我的待办事项列表中,而我的其他“有趣”项目都感觉不好玩那一周:)
Hope this helps.
希望这可以帮助。
回答by Lucero
You don't measure the number of threads in memory usage. Rather, take into account the number of "processors" (SMP / Multi-Cores / Hyper-Threading) to decide how many threads should run in parallel. Or use the ThreadPool, which is sized automatically to achieve a good thread-to-CPU ratio.
您不测量内存使用中的线程数。相反,考虑“处理器”(SMP/多核/超线程)的数量来决定应该并行运行多少线程。或者使用ThreadPool,它会自动调整大小以实现良好的线程与 CPU 比率。
回答by peSHIr
While I agree with the comments you've already received on your question, the use of System.Environment.WorkingSet
might perhaps be an actual answer to it if you really decide to take this course of action?
虽然我同意您已经收到的关于您的问题的评论System.Environment.WorkingSet
,但如果您真的决定采取这一行动,使用可能是对它的实际答案?