0

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?

helrich
  • 1,300
  • 1
  • 15
  • 34
  • How is it `stochastic` if it happens every time? It sounds like you closed a form and this is trying to access it afterwards. – OneFineDay Sep 26 '14 at 19:19
  • Are you sure the window still got a handle? If not `InvokeRequired` will return `False`. – Bjørn-Roger Kringsjå Sep 26 '14 at 19:48
  • @OneFineDay Yes I suppose I used the wrong word there, I was mainly referring to the fact that `Disposing` was returning `False` and then two lines later it is now `True`. @Bjørn-RogerKringsjå I don't think that is an issue, the exception occurs when `InvokeRequired` has already evaluated to `True`. Furthermore this method is only called from the other thread, so even evaluating `InvokeRequired` appears to be more of a sanity check than anything else. – helrich Sep 26 '14 at 19:52
  • @helrich Why do you check if the `theLabel` requires invoke and not the form? Change `If theLabel.InvokeRequired Then` to `If Me.InvokeRequired Then` and `Else` to `ElseIf (Me.Handle <> IntPtr.Zero) Then`. – Bjørn-Roger Kringsjå Sep 26 '14 at 19:59

0 Answers0