nexno
nexno

Reputation: 449

Threading System.NullReferenceException

I am trying to start and stop a autochecking function when checking or unchecking a checkbox.

    Private Sub CheckBoxautorefresh_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBoxautorefresh.CheckedChanged
    Dim AutoRefreshThread As Thread = Nothing
    If CheckBoxautorefresh.Checked Then
        AutoRefreshThread = New Threading.Thread(AddressOf Main.AutoRefresh)
        AutoRefreshThread.SetApartmentState(Threading.ApartmentState.STA)
        AutoRefreshThread.Start()
    Else
        AutoRefreshThread.Abort()
    End If
End Sub

When I check the Checkbox it starts AutoRefresh-Sub fine, and it works. When I unselect it after that, I get a System.NullReferenceException in this line:

   AutoRefreshThread.Abort()

The Autorefresh function just downloads a string every 30 seconds. And I like to check this autorefresh on/off with a checkbox. But for some reason it doesn't work. Can someone help me out? :)

Upvotes: 2

Views: 647

Answers (2)

dbasnett
dbasnett

Reputation: 11773

I am not a big fan of .Abort, a lot of gotchas. See http://msdn.microsoft.com/en-us/library/5b50fdsz%28v=vs.110%29.aspx

Try this pattern.

Dim thrd As Threading.Thread
Dim thrdStopped As New Threading.ManualResetEvent(False)

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
    If CheckBox1.Checked Then
        If IsNothing(thrd) OrElse thrd.ThreadState <> Threading.ThreadState.Background Then
            thrdStopped.Reset() '=false
            thrd = New Threading.Thread(AddressOf someThread)
            thrd.IsBackground = True
            thrd.Start()
        End If
    ElseIf Not IsNothing(thrd) AndAlso thrd.ThreadState = Threading.ThreadState.Background Then
        thrdStopped.Set() '=true
        thrd.Join()
    End If
End Sub

Private Sub someThread()
    Do
        Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff"))
    Loop While Not thrdStopped.WaitOne(100) 'loop while false, sleep 100 ms.
End Sub

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66489

You're defining the thread inside the CheckedChanged event:

Dim AutoRefreshThread As Thread = Nothing

When the checkbox is unchecked, you're referencing a variable that has not actually been instantiated (that only happens when the checkbox is checked). You're no longer referencing the original thread you created when the checkbox was checked.

Try defining AutoRefreshThread outside of the event.

Upvotes: 1

Related Questions