I'm working on an older system written in VB.NET, and it keeps throwing an exception when the application is closing because it's trying to access a disposed object. It occurs in a delegate that sets the text of a Label on the UI thread from another thread:
Private Sub SetWeightText_ThreadSafe(ByVal theLabel As Label, ByVal value As String)
If Not Me.IsDisposed AndAlso Not Me.Disposing Then
If theLabel.InvokeRequired Then
Dim theDelegate As New SetWeightText_Del(AddressOf SetWeightText_ThreadSafe)
'Exception here:
Me.Invoke(theDelegate, New Object() {theLabel, value})
Else
theLabel.Text = value
End If
End If
End Sub
The exception occurs at the line marked above, where the delegate is invoked. When the debugger stops here, the exception shows that the object (Me
) has been disposed, and sure enough, Me.Disposing
has become true, obviously sometime between that initial if
statement, and the delegate's invocation.
The exception is ObjectDisposedException was unhandled by user code
. I understand I could probably just wrap the whole thing in a Try..Catch
with an empty handler and be done with it, but I'd rather prevent the issue altogether.
And this occurs every time. How do I avoid this?