我开始知道 Thread.Suspend 不是无限期暂停线程的好方法。请让我知道是否有其他方法可以实现相同的目标。
提前致谢。
一个简短的 vb 示例
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
thrd.IsBackground = True
thrd.Start()
End Sub
Dim thrd As New Threading.Thread(AddressOf somethread)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'pause and resume
'first click pauses, second click resumes
reqpause.Set() 'set event
End Sub
Dim reqpause As New Threading.AutoResetEvent(False)
Private Sub somethread()
Do
'simulate work - your code here
Threading.Thread.Sleep(500)
Debug.WriteLine(DateTime.Now.ToLongTimeString)
'end simulate work
If reqpause.WaitOne(0) Then 'pause requested?
Debug.WriteLine("t-thrd paused")
reqpause.WaitOne() 'wait here for continuation
Debug.WriteLine("t-continue thrd")
End If
Loop
End Sub
使用Suspend
andResume
不是一个好主意。我不知道你为什么要永远等待,而是等待使用EventWaitHandle
等待。
private EventWaitHandle handle = new AutoResetEvent();
private void WorkerThread()
{
while(true)
{
handle.WaitOne();
}
}
//Forever is a long time
public void StopWaitingForever()
{
handle.Set();
}
其他更简单的方法是调用Sleep(Timeout.Infinite)
.
参考这里。