我有这些控制按钮(Windows.Forms的):如何终止/退出/中止旧线程工作并重新启动程序?
Start/Restart
| Pause
| Continue
一旦Start
被按下,创建threadPool[workerThreadsCount]
,ManualResetEvent mre
设置为mre.Set()
和线程开始做他们的工作。在一些伪代码中:
threadStartingPoint() {
int index = 0;
while(index !== someMaxCondition)
... // grab some data to work on
lock(_lock) { // lock index, so one access at a time
index += index;
}
... // do some stuff
_mre.WaitOne(); // Pause if button Pause is pressed.
}
}
工作线程像上面的例子一样工作在循环中。现在如果我按pause
,一切停止在_mre.Wait();
位置。用continue
我可以使用mre.Set()
打开大门,一切正常。现在的问题是当我Pause
,我想用户在Continue
或Restart
之间选择。 Restart
的问题是我不知道如何告诉我的线程退出while loop
。因为如果我只是设置mre.Set()
并创建新线程,一段时间以前,旧线程仍然可以使用旧数据循环。
有什么建议吗?
您需要使用具有超时值的'WaitOne'的重载。然后在while测试条件下,测试一些暂停或退出条件。 – GreatAndPowerfulOz
fyi'index'是线程本地的,你不需要锁定它,因为只有一个线程可以触摸它。 –