I'm trying to make sense of properly disposing of views and viewmodels in an mvvm environment. I hit upon one particular problem with various usercontrols (which in essence are my views) and their associated viewmodels in a docking environment (similar to the sort of thing you might see in visual studio).
I have read countless posts, blogs and questions here and finally found something which I thought was working (indeed it may well be but I just don't understand the process).
In my viewmodel I implement Idiposable and in the view (to which it is set as its datacontext) I ensure that the view calls dispose on its datacontext when it unloads. So view closes and calls dispose on its datacontext (my viewmodel) ensuring that I can clean up any left overs that might hang around and cause a memory leak like event handlers.
One such viewmodel has the following code in the overridden dispose sub:
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
'
'
If mwvm.CanCallDisposeOnErsSubmissionViewModel Then
mwvm = Nothing
subEd = Nothing
retEd = Nothing
End If
' TODO: set large fields to null.
End If
Try
If Not mwvm.CanCallDisposeOnErsSubmissionViewModel Then
disposedValue = False
End If
Catch ex As NullReferenceException
disposedValue = True
End Try
MessageBox.Show("DisposeValue = " & disposedValue.tostring)
End Sub
This viewmodel references elements in the mainviewmodel of the application (one of the reasons why I felt it was important to clean it up after use. However the view for which it is the data context gets redrawn if the end user either adds or closes other windows in the docksite in which it sits (hence the need for a conditional statement).
Now this may not be elegant, and it may very well not be the correct way to do this but my question arises from observing the following.
When I choose to actively close the view and the conditional statements allow the clean-up to take place and set the disposed value to true I would have thought that that would mean that the view model had been well and truly closed and disposed of, however I can let the program continue running and hey presto up pops a message box which can only have come from the handler above. So is my model properly disposed off, is this normal behaviour (presumably the garbage collector doing its thing so it can be ignored) or is there a fundamental error on my part somewhere?