简体   繁体   English

清理方法中的变量

[英]Cleaning up variables in methods

I am having some memory issues in a large piece of software I work on, I am looking through methods we have written where we are declaring variables at the beginning of the method, but they are not being cleaned (nullified or disposed) at the end of the method. 我正在使用的大型软件中存在一些内存问题,正在查看我们编写的方法,这些方法在方法的开头声明了变量,但最后并未将其清除(清空或处置)方法的。

public static bool CheckIsNumber(string x)
{
    int y;
    return(int.TryParse(x, out y));
}

as you see above, y is never set to null or disposed or anything like that, I always thought it would be picked up by the GC, but after looking through a memory profiler, I am not so sure anymore. 正如您在上面看到的, y永远不会设置为null或处置或类似的东西,我一直认为它会被GC拾取,但是在查看内存分析器后,我就不再那么确定了。

There's a distinction between a variable going out of scope and garbage collection in .NET. .NET中的变量超出范围与垃圾回收之间存在区别。 Microsoft lists three conditions that will trigger garbage collection: Microsoft列出了将触发垃圾收集的三个条件:

  1. The system has low physical memory. 系统的物理内存不足。
  2. The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. 托管堆上分配的对象使用的内存超过了可接受的阈值。
  3. The GC.Collect method is called. 调用GC.Collect方法。

Source: http://msdn.microsoft.com/en-us/library/ee787088(v=vs.110).aspx#conditions_for_a_garbage_collection 来源: http : //msdn.microsoft.com/zh-cn/library/ee787088(v=vs.110).aspx#conditions_for_a_garbage_collection

When I've looked at memory usage of my .NET apps, they generally rise steadily to a certain point after which the Garbage Collector collects and the memory usage drops again. 当我查看.NET应用程序的内存使用情况时,它们通常会稳定上升到某个点,然后垃圾收集器会收集该内存,然后内存使用率会再次下降。 The best I can tell that's exactly how it's meant to work. 我能说的最好的就是它的工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM