使用线程的方法调用数组

时间:2015-04-28 08:17:47

标签: multithreading winforms delegates

我正在使用Windows Form Application。在那里,我有一个类,它由5种不同的方法组成。所有这些都是使用线程从各种来源填充私人成员。

为此,我使用以下代码片段来调用方法

Dim threadForMethod1 As Threading.Thread
threadForMethod1 = New Threading.Thread(AddressOf Method1)
threadForMethod1.Start()

现在我想为线程添加开/关开关。顺便说一句,如果我关闭开关,所有方法都应该使用主线程执行。

实施它的最佳方式是什么。

1 个答案:

答案 0 :(得分:0)

您可以使用以下类:

Imports System.Threading

Public Class ThreadHandler

    Dim t1 As New Thread(AddressOf M1)
    Dim t2 As New Thread(AddressOf M2)

    Public Sub M1()
        Thread.Sleep(3000)
        MsgBox("M1")
    End Sub

    Public Sub M2()
        Thread.Sleep(3000)
        MsgBox("M2")
    End Sub

    Public Sub StartAll()
        If t1.ThreadState <> ThreadState.Unstarted Then
            t1 = New Thread(AddressOf M1)
        End If
        If t2.ThreadState <> ThreadState.Unstarted Then
            t2 = New Thread(AddressOf M2)
        End If

        t1.Start()
        t2.Start()

    End Sub

    Public Sub StopAll()

        t1.Abort()
        t2.Abort()

    End Sub

End Class

使用上述类:

Private th As New ThreadHandler()

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    th.StartAll()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    th.StopAll()
End Sub