简体   繁体   中英

Do I need to dispose IDisposable that have the same lifetime as the application itself?

I have an IDiposable object that lives "forever" in the application. In my case that is SemaphoreSlim , but the question applies really to any objects that can be disposed.

I know for sure that I need an object for as long as the application runs. So the question is: do I really need to ensure it is disposed or all unmanaged resources are freed anyway when the process ends? (Both Windows and Linux if that matters).

The problem with disposing is that I have my semaphore deep in the stack and theoretically that means that my whole stack of objects has to implement IDisposable just because somewhere there is a semaphore that really never needs to get disposed.

I want to avoid but not sure about consequences.

I have an IDiposable object that lives "forever" in the application

Well if it has to live till application life time then where is the question of disposing? Rather have it freed by the run time when your application ends or recycles.

all unmanaged resources are freed anyway when the process ends?

Yes they gets freed away once your application ends (process ends) but till then the resource sits there occupying memory (but that's what looks like your requirement is)

All OS level objects are freed up with a process termination. This is guaranteed by OS and is true for both Windows and Linux operating systems. Additionally, IDispisable with properly implemented dispose pattern has failsafe mechanism which ensures that unmanaged resources are reclaimed during finalization process. This process however has some limitations (in particular the finalizers are given with limited period of time they should complete). So as worst case scenario you can be sure that unmanaged resources won't outlive your process. It's of course not a best practice to leave them unattended as it can lead to resource and memory leacks in case of systematic ignoring of resource reclaiming but as exceptional case for a single resource with lifetime equivalent to application lifetime it can be acceptable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM