线程System.NullReferenceException

时间:2014-03-23 11:53:04

标签: vb.net multithreading 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

当我检查复选框时,它启动AutoRefresh-Sub罚款,它可以工作。当我在那之后取消选择它时,我在这一行中得到一个System.NullReferenceException:

   AutoRefreshThread.Abort()

Autorefresh功能每30秒下载一个字符串。 我想用一个复选框来检查这个autorefresh开/关。 但由于某种原因,它不起作用。 有人可以帮我吗? :)

2 个答案:

答案 0 :(得分:1)

您正在CheckedChanged事件中定义线程:

Dim AutoRefreshThread As Thread = Nothing

取消选中该复选框后,您将引用尚未实例化的变量(仅在选中复选框时才会发生)。在复选框被选中时,您不再引用您创建的原始主题。

尝试在事件之外定义AutoRefreshThread

答案 1 :(得分:1)

我不是很喜欢.Abort,很多陷阱。见http://msdn.microsoft.com/en-us/library/5b50fdsz%28v=vs.110%29.aspx

尝试这种模式。

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