gpt4 book ai didi

c# - 如何从代码中监控内存分配

转载 作者:行者123 更新时间:2023-11-30 12:42:47 30 4
gpt4 key购买 nike

我有一个最终抛出“内存不足”异常的 Windows 服务。它用 C# 编写并在 Windows 7 上运行。

是的,我已经在 Stack Overflow 以及互联网上的其他地方阅读了有关此问题的现有问题。事实上,我发现埃里克·利珀特 (Eric Lippert) 的一篇很棒的文章“内存不足”并不指物理内存,他在其中对这种情况提供了非常清楚的解释。

http://blogs.msdn.com/b/ericlippert/archive/2009/06/08/out-of-memory-does-not-refer-to-physical-memory.aspx?PageIndex=1#comments

在这篇文章中,他用以下语句提到“内存不足”:“现在用词不当。它实际上应该是“无法找到足够的连续地址空间”错误;内存充足因为内存等于磁盘空间"。

他还说:

An “out of memory” error almost never happens because there’s not enough storage available; as we’ve seen, storage is disk space, and disks are huge these days. Rather, an “out of memory” error happens because the process is unable to find a large enough section of contiguous unused pages in its virtual address space to do the requested mapping.

当我查看 PerfMon 中的服务时,我看到在 Memory for Commit、Working Set 和 Private 下的列都在不断增长。我确定有一些字符串不断被添加到或者一些列表没有被清除。

我的问题是,我可以使用 C# 中的某些技术来监控代码本身对单个对象或集合的内存请求,例如可以监控系统的类库吗? 如果是这样,我可以从代码本身内部监视连续的内存请求。

最佳答案

使用 C# 代码告诉您 Windows 服务消耗了多少。

private float GetActuratePrivateWorkingSet(Process currentProcess)
{
// get the physical mem usage for this process
var pc = new PerformanceCounter("Process", "Working Set - Private", currentProcess.ProcessName, true);
pc.NextValue();
Thread.Sleep(1000);
var privateWorkingSet = pc.NextValue()/ 1024/1024;
return privateWorkingSet;
}

您很可能有一些错误的代码,而不是真正的内存不足。 - 内存泄漏是由于未关闭与资源的连接而不是代码引起的。苏打话......C# 垃圾收集将释放托管资源。

寻找 C# 静态对象...你不应该在 Windows 服务中有 ANY 除非你真的知道它为什么在那里并且它被用作帮助程序。

Windows 服务通常用于轮询某事......在轮询的工作中......除了帮助程序之外,不应将任何静态类用于任何其他用途。

如果您提供有关 Windows 服务功能的更多上下文......那么可以提出更好的建议。

附言。回答你的问题:red-gate 的 Ant Memory profiler 非常好。但我敢打赌,只要了解代码的作用,您就能更快地找到它。

关于c# - 如何从代码中监控内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653094/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com