Do you need to dispose of objects and set them to null?

前端 未结 11 1834
不思量自难忘°
不思量自难忘° 2020-11-22 10:58

Do you need to dispose of objects and set them to null, or will the garbage collector clean them up when they go out of scope?

11条回答
  •  不思量自难忘°
    2020-11-22 11:37

    If the object implements IDisposable, then yes, you should dispose it. The object could be hanging on to native resources (file handles, OS objects) that might not be freed immediately otherwise. This can lead to resource starvation, file-locking issues, and other subtle bugs that could otherwise be avoided.

    See also Implementing a Dispose Method on MSDN.

提交回复
热议问题