Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I ensure disposal of possibly disposable objects?

I am working on a .NET project, which needs to interact with some user defined classes - reffered to as "jobs". All job classes must implement a specific interface IJob in order order for the library to consume them. Sometimes a job class might hold unmanaged resource, which needs to be explicitly disposed.

How should I ensure that all jobs are properly disposed after use, if I do not know in advance if the job needs explicit disposal? I have a few ideas myself, but would like to hear your comments/suggestions:

  1. Make IJob : IDisposable, forcing all jobs to implement a Dispose() method. This will allow me to work with jobs in using blocks, but as most jobs are not expected to need explicit disposal, this might add unneeded confusion for the client developers.

  2. Do all work involving jobs in try-finally blocks, and use finally to ensure that Dispose() is called if the job implements IDisposable. This makes it easier for clients to implement a new job class - by not having to implement an empty Dispose() method - but it also hides the fact that the library knows and cares about disposable jobs.

After writing this up, I tend to lean towards solution #1, but I still think it would be nice to see alternative solutions, and additional pros/cons to the two I already have in mind.

like image 236
Jørn Schou-Rode Avatar asked Dec 29 '09 17:12

Jørn Schou-Rode


People also ask

How do you ensure proper waste disposal?

Proper waste disposal and management can be done by applying the 3R – Reduce, Reuse and Recycle. Reducing means lessening the amount of trash/garbage produced. Reusing refers to using materials more than once while recycling means creating new material or product out of trash/garbage.


1 Answers

There is a precedent: The Stream base class is IDisposable nad therefore all Streams descendants are. But MemoryStream doesn't need Disposing.
But don't aim for try/finally, the using() { } block is a more convenient shorthand.

So your choice is: Do you want all Jobs to be IDisposable or just some?

The first option incurs a small overhead, the second one makes it easier to forget Dispose (using) when it is necessary.

like image 99
Henk Holterman Avatar answered Sep 21 '22 11:09

Henk Holterman