Search code examples
c#disposestatic-analysis

CA2213 triggers when using null conditional operator in dispose pattern


I am working on a code base that considers static code analysis design warnings as errors.

When I implement my Dispose() method like this:

public void Dispose()
{
     threadPool?.Dispose();
     GC.SuppressFinalize(this);
}

The error I get

error CA1063: Microsoft.Design : Modify 'HandlerBase.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.

So I modify it to follow the pattern expected by CA1063

protected virtual void Dispose(bool disposing)
{
     if (disposed)
     {
         return;
     }

     if (disposing)
     {
         threadPool?.Dispose();
     }

     disposed = true;
}

 public void Dispose()
{
     Dispose(true);
     GC.SuppressFinalize(this);
 }

And it no longer realizes that I'm disposing the object:

error CA2213: Microsoft.Usage : 'HandlerBase' contains field 'HandlerBase.threadPool' that is of IDisposable type: 'SemaphoreSlim'. Change the Dispose method on 'HandlerBase' to call Dispose or Close on this field.


Solution

  • As suspected, it seems to be a bug with the Roslyn Analyser.

    CA2213 triggers when using null conditional operator #291

    It seems to be fixed in later versions (if I read correctly); however, if that is not applicable to you, or it's still not working you can suppress the warning/error or just remove the null conditional and check for null manually:

    if(threadPool != null)
       threadPool.Dispose();