1

我开始知道 Thread.Suspend 不是无限期暂停线程的好方法。请让我知道是否有其他方法可以实现相同的目标。

提前致谢。

4

3 回答 3

1

一个简短的 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
于 2013-07-31T14:30:33.057 回答
0

使用SuspendandResume不是一个好主意。我不知道你为什么要永远等待,而是等待使用EventWaitHandle等待。

private EventWaitHandle handle = new AutoResetEvent();

private void WorkerThread() 
{
    while(true) 
    {
        handle.WaitOne();
    }
}
//Forever is a long time 
public void StopWaitingForever()
{
    handle.Set();
}
于 2013-07-31T14:27:29.740 回答
0

其他更简单的方法是调用Sleep(Timeout.Infinite).

参考这里

于 2015-12-09T09:57:07.783 回答