What are ways to solve Memory Leaks in C#

前端 未结 10 1791
生来不讨喜
生来不讨喜 2021-02-14 14:50

I\'m learning C#. From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be. I\'m looking for wisdom learn

相关标签:
10条回答
  • 2021-02-14 15:47

    C#, the .NET Framework uses Managed Memory and everything (but allocated unmanaged resources) is garbage collected.

    It is safe to assume that managed types are always garbage collected. That includes arrays, classes and structures. Feel free to do int[] stuff = new int[32]; and forget about it.

    If you open a file, database connection, or any other unmanaged resource in a class, implement the IDisposable interface and in your Dispose method de-allocate the unmanaged resource.

    Any class which implements IDisposable should be explicitly closed, or used in a (I think cool) Using block like;

    using (StreamReader reader = new StreamReader("myfile.txt"))
    {
       ... your code here
    }
    

    Here .NET will dispose reader when out of the { } scope.

    0 讨论(0)
  • 2021-02-14 15:50

    You can use tools like CLR profiler it takes some time to learn how to use it correctly, but after all it is free. (It helped me several times to find my memory leakage)

    0 讨论(0)
  • 2021-02-14 15:50

    One other thing to consider for memory management is if you are implementing any Observer patterns and not disposing of the references correctly.

    For instance: Object A watches Object B Object B is disposed if the reference from A to B is not disposed of property the GC will not properyly dispose of the object. Becuase the event handler is still assigned the GC doesn't see it as a non utilized resource.

    If you have a small set of objects you're working with this may me irrelevant. However, if your working with thousands of objects this can cause a gradual increase in memory over the life of the application.

    There are some great memory management software applications to monitor what's going on with the heap of your application. I found great benefit from utilizing .Net Memory Profiler.

    HTH

    0 讨论(0)
  • 2021-02-14 15:51

    I recommend using .NET Memory Profiler

    .NET Memory Profiler is a powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language.

    .NET Memory Profiler will help you to:

    • View real-time memory and resource information
    • Easily identify memory leaks by collecting and comparing snapshots of .NET memory
    • Find instances that are not properly disposed
    • Get detailed information about unmanaged resource usage
    • Optimize memory usage
    • Investigate memory problems in production code
    • Perform automated memory testing
    • Retrieve information about native memory

    Take a look at their video tutorials:

    http://memprofiler.com/tutorials/

    0 讨论(0)
提交回复
热议问题