Should IDisposable.Dispose() be made safe to call multiple times?

前端 未结 4 1661
一向
一向 2020-11-30 08:08

Should implementations of IDisposable make Dispose() safe to call multiple times? Or the opposite? What approach to most .NET Framework classes take?

Specifically, i

4条回答
  •  广开言路
    2020-11-30 08:57

    Objects should be tolerant to having Dispose called more than once, since--especially in the presence of exceptions--it may be difficult for cleanup code to know for certain which things have been cleaned up and which have not. Nulling out IDisposable fields as they are cleaned up (and being tolerant of ones that are already null) will make it easier to avoid redundant calls to Dispose, but it doesn't really cost anything to make objects tolerate multiple disposal, and it helps to avoid ickiness in some Exception-throwing situations.

提交回复
热议问题