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

前端 未结 4 1655
一向
一向 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 09:02

    Yes, your implementations of IDisposable.Dispose() should tolerate being called multiple times. After the first call to Dispose(), all other calls can just return immediately.

    I would prefer the first part of your code example, to dispose and null the local variables as you go.

    Be aware that your .Dispose() may be called multiple times even if you implement Dispose and null patterns in your code. If multiple consumers hold a reference to the same disposable object, then that object's Dispose will probably be called multiple times as those consumers drop their references to it.

提交回复
热议问题