Release resources in .Net C#

前端 未结 6 1501
庸人自扰
庸人自扰 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条回答
  •  遇见更好的自我
    2021-02-19 11:53

    Resources are of two kinds - managed, and unmanaged. Managed resources will be cleaned up by the garbage collector if you let it - that is, if you release any reference to the object. However, the garbage collection does not know how to release unmanaged resources that a managed object holds - file handles, and other OS resources for example.

    IDisposable is best practice when there's a managed resource you want released promptly (like a database connection), and vital when there are unmanaged resources which you need to have released. The typical pattern:

    public void Dispose()
    protected void Dispose(bool disposing)
    

    Lets you ensure that unmanaged resources are released whether by the Dispose method or by object finalisation.

提交回复
热议问题