|
-
May 21st, 2009, 10:18 PM
#1
Thread Starter
Frenzied Member
When to use IDisposable?
Hello,
I have been working on this for a while now. And I am still confused about some issues. My questions below
1) I know that you only need a finalizer if you are disposing of unmanaged resources. However, if you are using managed resources that make calls to unmanaged resources. Would you still need to implement a finalizer?
2) However, if you develop a class that doesn't use any unmanged resources directly or indirectly and you implement the IDisposable so that clients of your class can use the 'using statement'. Would it be acceptable to implement the IDisposable just so that clients of your class can use the using statement?
Code:
myClass objClass = new myClass()
using objClass
'Do work here
End Using
3) I have developed this simple code below to demostrate the Finalize/dispose pattern:
Code:
Public Class NoGateway
Implements IDisposable
Private wc As WebClient = Nothing
Public Sub New()
wc = New WebClient()
Using wc
AddHandler wc.DownloadStringCompleted, AddressOf wc_DownloadStringCompleted
End Using
End Sub
' Start the Async call to find if NoGateway is true or false
Public Sub NoGatewayStatus()
' Start the Async's download
wc.DownloadStringAsync(New Uri(www.xxxx.xxx))
' Do other work here
End Sub
Private Sub wc_DownloadStringCompleted(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
' Do work here
End Sub
' Dispose of the NoGateway object
Public Sub Dispose()
RemoveHandler wc.DownloadStringCompleted, AddressOf wc_DownloadStringCompleted
wc.Dispose()
GC.SuppressFinalize(Me)
End Sub
End Class
Question about the source code:
1) Here I have not added the finalizer. And normally the finalizer will be called by the GC, and the finalizer will call the Dispose. As I don't have the finalizer, when do I call the Dispose method? Is it the client of the class that has to call it?
2) I have added my RemoveHandler in the Dispose method. Is this the place I should be removing it?
3) I am using the 'using statement' to create the webclient. However, is this bad design as when the code executes at the end of the 'using statement' the webclient object will no longer exist?
4) I am using the webclient class in my 'NoGateway' class. Because the webclient implements the IDisposable interface. Does this mean that the webclient indirectly uses unmanaged resources? Is there any hard and fast rule to follow about this. How do I know that a class uses unmanaged resources?
5) Is my source correctly implementing the Finalize/Dispose pattern if the webclient is using unmanaged resources.
Sorry for the long list of questions here. However, just trying to get this 100% clear to me.
Many thanks,
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|