What are ways to solve Memory Leaks in C#

前端 未结 10 1774
生来不讨喜
生来不讨喜 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.

提交回复
热议问题