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:
Make
IJob : IDisposable
, forcing all jobs to implement aDispose()
method. This will allow me to work with jobs inusing
blocks, but as most jobs are not expected to need explicit disposal, this might add unneeded confusion for the client developers.Do all work involving jobs in
try-finally
blocks, and usefinally
to ensure thatDispose()
is called if the job implementsIDisposable
. This makes it easier for clients to implement a new job class - by not having to implement an emptyDispose()
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.