暂停按钮上的线程单击按钮上的恢复

时间:2012-07-14 03:56:46

标签: .net vb.net multithreading

我有一个从某些网站获取数据的循环,该循环需要大约一个小时来获取数据并将其填充到数据库中,此循环位于一个线程中,我想添加一个暂停该按钮的按钮线程,直到再次单击该按钮,它将恢复停止的位置。 我怎么能以安全的方式做到这一点?

2 个答案:

答案 0 :(得分:1)

这是一个简单的Windows控制台应用程序;它使用布尔标志来指示线程是否应该处理。我希望这能指出你正确的方向。

Module Module1

    Private _ThreadControl_Run As Boolean = False

    Sub Main()
        Dim thread As New System.Threading.Thread(AddressOf ThreadWorker)
        thread.IsBackground = True
        thread.Start()

        _ThreadControl_Run = True
        Console.WriteLine("Main() _ThreadControl_Run = " & _ThreadControl_Run.ToString())
        System.Threading.Thread.Sleep(1000)

        _ThreadControl_Run = False
        Console.WriteLine("Main() _ThreadControl_Run = " & _ThreadControl_Run.ToString())
        System.Threading.Thread.Sleep(1000)

        _ThreadControl_Run = True
        Console.WriteLine("Main() _ThreadControl_Run = " & _ThreadControl_Run.ToString())
        System.Threading.Thread.Sleep(1000)

        _ThreadControl_Run = False
        Console.WriteLine("Main() _ThreadControl_Run = " & _ThreadControl_Run.ToString())
        System.Threading.Thread.Sleep(1000)
    End Sub

    Private Sub ThreadWorker()
        Do While True
            If (_ThreadControl_Run) Then
                Console.WriteLine("     ThreadWorker()")
                System.Threading.Thread.Sleep(100)
            End If
        Loop
    End Sub

End Module

答案 1 :(得分:0)

试试这个:

Public Sub PauseThreadButton_Click(sender As System.Object, e As System.EventArgs) Handles PauseThreadButton.Click
    'REM: Next line puts your thread in a suspended state
    TheThread.Suspend()
End Sub

要恢复:

Public Sub ResumeThreadButton_Click(sender As System.Object, e As System.EventArgs) Handles ResumeThreadButton.Click
    'REM: Next line resumes your thread
    TheThread.Resume()
End Sub