How does one tell if an IDisposable object referen

2019-01-23 10:19发布

Is there a method, or some other light-weight way, to check if a reference is to a disposed object?

P.S. - This is just a curiousity (sleep well, not in production code). Yes, I know I can catch the ObjectDisposedException upon trying to access a member of the object.

8条回答
Animai°情兽
2楼-- · 2019-01-23 11:02

What I like to do is declare the objects without initializing them, but set their default values to Nothing. Then, at the end of the loop I write:

If anObject IsNot Nothing Then anObject.Dispose()

Here is a complete sample:

Public Sub Example()
    Dim inputPdf As PdfReader = Nothing, inputDoc As Document = Nothing, outputWriter As PdfWriter = Nothing

    'code goes here that may or may not end up using all three objects, 
    ' such as when I see that there aren't enough pages in the pdf once I open  
    ' the pdfreader and then abort by jumping to my cleanup routine using a goto ..

GoodExit:
    If inputPdf IsNot Nothing Then inputPdf.Dispose()
    If inputDoc IsNot Nothing Then inputDoc.Dispose()
    If outputWriter IsNot Nothing Then outputWriter.Dispose()
End Sub

This also works great for putting your main objects at the top of a routine, using them inside a Try routine, and then disposing them in a Finally block:

Private Sub Test()
    Dim aForm As System.Windows.Forms.Form = Nothing
    Try
        Dim sName As String = aForm.Name  'null ref should occur
    Catch ex As Exception
        'got null exception, no doubt
    Finally
        'proper disposal occurs, error or no error, initialized or not..
        If aForm IsNot Nothing Then aForm.Dispose()
    End Try
End Sub
查看更多
萌系小妹纸
3楼-- · 2019-01-23 11:03

System.Windows.Forms.Control has an IsDisposed property which is set to true after Dispose() is called. In your own IDisposable objects, you can easily create a similar property.

查看更多
登录 后发表回答