我应该如何确保处置可能是一次性的对象?对象

2023-09-04 09:28:32 作者:?爱他怎样毁我如何、

我工作的一个.NET项目,它需要与一些用户定义的类交互 - 下文称为工作。所有作业类必须实现,以便为了特定的接口 IJob 的消耗他们的图书馆。有时,作业类可能拥有非托管资源,需要加以明确的处理。

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:

IJob:IDisposable的,迫使所有作业实施的Dispose()方法。这将允许有工作在使用块我的工作,但由于大多数工作是的没有的预计需要明确的处理,这可能会增加不必要的混淆客户端的开发者。

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.

执行涉及作业时全部工作尝试,终于块,并使用最后来确保的Dispose()被称为如果作业机具的IDisposable 。这使得它更容易为客户实施新的作业类 - 通过不执行空的Dispose()方法 - 但它也隐藏了该库知道和关心的事实有关一次性就业机会。

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.

写这以后,我倾向于倾向于解决方案#1,但我仍然认为这将是很好看的替代解决方案,以及额外的优点/缺点两个我心中已经有了。

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.

推荐答案

有一个precedent:流基类是IDisposable的NAD因此所有的流后裔。但MemoryStream的并不需要优化配置。 但是不要瞄准尝试/最后,使用(){} 块是一个更方便的速记。

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.

所以,你的选择是:你希望所有乔布斯成为了IDisposable或只是一些?

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

第一个选项招致通过少的开销,第二个更容易忘记的Dispose(使用)时,它是必要的。

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