Should IDisposable.Dispose() implementations be idempotent?

前端 未结 4 1287
旧时难觅i
旧时难觅i 2020-12-18 18:28

The Microsoft.NET framework provides the IDisposable interface which requires an implementation of void Dispose() method. Its purpose is to enable

4条回答
  •  孤城傲影
    2020-12-18 19:18

    Personally - Yes - I always make Dispose() idempotent.

    During the usual life-cyle of an object in a given application it may not be necessary - the life-cyle from creation to disposal may be deterministic and well known.

    However, equally, in some applications it might not be so clear.

    For example, in a decorator scenario: I may have a disposable object A, decorated by another disposable object B. I may want to explicitly dispose A, and yet Dispose on B may also dispose the instance it wraps (think: streams).

    Given it is relatively easy to make Dispose idempotent (ie if already disposed, do nothing), it seems silly not to.

提交回复
热议问题