Release resources in .Net C#

前端 未结 6 1519
庸人自扰
庸人自扰 2021-02-19 11:19

I\'m new to C# and .NET, ,and have been reading around about it.

I need to know why and when do I need to release resources? Doesn\'t the garbage collector take care of

6条回答
  •  猫巷女王i
    2021-02-19 11:44

    Basically, you need to worry about releasing resources to unmanaged code - anything outside the .NET framework. For example, a database connection or a file on the OS.

    The garbage collector deals with managed code - code in the .NET framework.

    Even a small application may need to release unmanaged resources, for example it may write to a local text file. When you have finished with the resource you need to ensure the object's Dispose method is called. The using statement simplifies the syntax:

    using (TextWriter w = File.CreateText("test.txt"))
    {
        w.WriteLine("Test Line 1");
    }
    

    The TextWriter object implements the IDisposable interface so as soon as the using block is finished the Dispose method is called and the object can be garbage collected. The actual time of collection cannot be guaranteed.

    If you create your own classes that need to be Disposed of properly you will need to implement the IDisposable interface and Dispose pattern yourself. On a simple application you probably won't need to do this, if you do this is a good resource.

提交回复
热议问题