Release resources in .Net C#

前端 未结 6 1503
庸人自扰
庸人自扰 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 12:03

    You don't need to release memory in managed objects like strings or arrays - that is handled by the garbage collector.

    You should clean up operating system resources and some unmanaged objects when you have finished using them. If you open a file you should always remember to close that file when you have finished using it. If you open a file exclusively and forget to close, the next time you try to open that file it might still be locked. If something implements IDisposable, you should definitely consider whether you need to close it properly. The documentation will usually tell you what the Dispose method does and when it should be called.

    If you do forget, the garbage collector will eventually run the finalizer which should clean up the object correctly and release the unmanaged resources, but this does not happen immediately after the object becomes eligible for garbage collection, and it in fact might not run at all.

    Also it is useful to know about the using statement.

提交回复
热议问题