简体   繁体   中英

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.

There's a distinction between a variable going out of scope and garbage collection in .NET. Microsoft lists three conditions that will trigger garbage collection:

  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.

Source: http://msdn.microsoft.com/en-us/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. The best I can tell that's exactly how it's meant to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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