在这段代码中,我想使用AutoResetEvent和bool变量暂停/恢复一个线程.如果阻塞== true,是否可以在每次测试时暂停(在for循环中工作())?测试"阻塞"变量也需要锁定,我认为这是耗时的.
class MyClass
{
AutoResetEvent wait_handle = new AutoResetEvent();
bool blocked = false;
void Start()
{
Thread thread = new Thread(Work);
thread.Start();
}
void Pause()
{
blocked = true;
}
void Resume()
{
blocked = false;
wait_handle.Set();
}
private void Work()
{
for(int i = 0; i < 1000000; i++)
{
if(blocked)
wait_handle.WaitOne();
Console.WriteLine(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)
是的,你可以通过使用a来避免你正在进行的测试ManualResetEvent.
该ManualResetEvent将让你的线程传递,只要它是"设置"(信号),但不同的是AutoResetEvent,你以前,它不会自动为线程通过其复位.这意味着您可以将其设置为允许在循环中工作,并可以将其重置为暂停:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4535 次 |
| 最近记录: |