Dealing with .NET IDisposable objects

后端 未结 12 764
自闭症患者
自闭症患者 2021-01-30 13:14

I work in C#, and I\'ve been pretty lax about using using blocks to declare objects that implement IDisposable, which you\'re apparently always suppose

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 14:00

    I don't really have anything to add to the general use of Using blocks but just wanted to add an exception to the rule:

    Any object that implements IDisposable apparently should not throw an exception during its Dispose() method. This worked perfectly until WCF (there may be others), and it's now possible that an exception is thrown by a WCF channel during Dispose(). If this happens when it's used in a Using block, this causes issues, and requires the implementation of exception handling. This obviously requires more knowledge of the inner workings, which is why Microsoft now recommends not using WCF channels in Using blocks (sorry could not find link, but plenty other results in Google), even though it implements IDisposable.. Just to make things more complicated!

提交回复
热议问题