views:

91

answers:

2

Possible Duplicate:
Am I implementing IDisposable correctly?

Hi,

I am referring this post to check the use of IDisposable.

I see an issue in Dispose method here. In the code "disposed" is used only in the

private void Dispose(bool disposing) 

method.

I believe it should be used before calling the "Dipose" method and correct implementation would be

public void Dispose()
        {
            if(!disposed )
            {
            Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
            }
        }

Am I thinking correct?

+1  A: 

Given that the implementation of Dispose(disposing) checks the disposed flag anyway, why bother doing it in the Dispose() method as well?

The only downside would be that GC.SuppressFinalize could be called multiple times if you call Dispose() multiple times - but that's harmless as far as I'm aware.

Jon Skeet
I think I should remove the check from Dispose(disposing) and put it in "Dispose".
Ram
@Ram: No, that way the Finalizer might do something double and that is not always harmless.
Henk Holterman
But isn't it logical that we should not call "SuppressFinalize" if object is disposed? or "SuppressFinalize" is called once for that object.
Ram
Why do you think that? The only efect would be to prevent `GC.SuppressFinalize` being called multiple times, if `Dispose()` was also called multiple times. Are you perhaps over thinking this, what bug or behaviour are you trying to avoid with this change.
Ben Robinson
@Ben - Well , After looking in the code, I just thought about that if the bool diposed is there. It should be used more logically.
Ram
+1  A: 

And don't forget to clear up any unmanaged resources. Microsoft gives sample code here:

"Implement IDisposable Correctly" http://msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx

-Krip

Krip
Surely that would be handled in the `Dispose(disposing)` code. Isn't this question about when to call that method?
Jon Skeet