Yes, you can avoid the test you are performing by using a ManualResetEvent
.
The ManualResetEvent
will let your thread pass as long as it is "set" (signalled), but unlike the AutoResetEvent
you had previously, it doesn't automatically reset as a thread passes it. This means you can leave it Set to allow work in your loop, and can Reset it to pause:
class MyClass
{
// set the reset event to be signalled initially, thus allowing work until pause is called.
ManualResetEvent wait_handle = new ManualResetEvent (true);
void Start()
{
Thread thread = new Thread(Work);
thread.Start();
}
void Pause()
{
wait_handle.Reset();
}
void Resume()
{
wait_handle.Set();
}
private void Work()
{
for(int i = 0; i < 1000000; i++)
{
// as long as this wait handle is set, this loop will execute.
// as soon as it is reset, the loop will stop executing and block here.
wait_handle.WaitOne();
Console.WriteLine(i);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…