我有一个从某些网站获取数据的循环,该循环大约需要一个小时才能获取数据并将其填充到数据库中,这个循环在一个线程中,我想添加一个暂停线程的按钮,直到再次单击按钮,它会从停止的地方恢复。我怎样才能以安全的方式做到这一点?
问问题
1662 次
2 回答
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
于 2012-07-16T20:59:56.120 回答
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
于 2012-07-16T15:14:54.270 回答