Dealing with .NET IDisposable objects

后端 未结 12 768
自闭症患者
自闭症患者 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 13:48

    In short, it's not the end of the world if I miss a using. I just wish something would generate at least a warning for it.

    The problem here is that you can't always deal with an IDisposable by just wrapping it up in a using block. Sometimes you need the object to hang around for a bit longer. In which case you will have to call its Dispose method explicitly yourself.

    A good example of this is where a class uses a private EventWaitHandle (or an AutoResetEvent) to communicate between two threads and you want to Dispose of the WaitHandle once the thread is finished.

    So it isn't as simple as some tool just checking that you only create IDisposable objects within a using block.

提交回复
热议问题