Should I bother calling dispose on objects which share lifetime of process?

亡梦爱人 提交于 2019-12-04 03:24:24

It depends on the object (resource) in question.

When a process terminates all unmanaged memory, filehandles and other OS resources will be released, even if the associated finalizers failed to run.

But I'm not so sure about db handles, named-mutexes etc.

So before you could consider it safe to not call Dispose, you would have to know about the resource type and how it relates to the process. Much easier to just call Dispose() out of general principle.

But it is a theoretical argument, most classes will use SafeHandle : CriticalFinalizerObject . So I don't think it ever is a real practical problem.

No. By design, IDisposable is available to allow a program to release an unmanaged resource early, earlier than it could be done by the finalizer. Which runs at a fairly unpredictable time, usually later whenever a garbage collection is performed. You cannot predict when that happens.

There's no point in disposing at program exit, the finalizer is guaranteed to run just before the AppDomain is unloaded and the process shuts down.

That's said, there is some IDisposable abuse about, code that actually expects you to call it. But that's typically based on the using statement, so not so likely you'll run into that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!