Do I need to call Close() on a ManualResetEvent?

前端 未结 6 963
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 11:43

I\'ve been reading up on .NET Threading and was working on some code that uses a ManualResetEvent. I have found lots of code samples on the internet. However, when reading

6条回答
  •  庸人自扰
    2020-12-10 12:43

    In general, if an object implements IDisposable it is doing so for a reason and you should call Dispose (or Close, as the case may be). In the example you site, the ManualResetEvent is wrapped inside a using statement, which will "automatically" handle calling Dispose. In this case, Close is synonymous with Dispose (which is true in most IDisposable implementations that provide a Close method).

    The code from the example:

    using (var mre = new ManualResetEvent(false))
    {
       ...
    }
    

    expands to

    var mre = new ManualResetEvent(false);
    try
    {
       ...
    }
    finally
    {
       ((IDispoable)mre).Dispose();
    }
    

提交回复
热议问题