C# 暂停/恢复带有AutoResetEvent的线程

C# 暂停/恢复带有AutoResetEvent的线程,c#,.net,multithreading,C#,.net,Multithreading,在这段代码中,我想使用AutoResetEvent和bool变量暂停/恢复线程。 如果blocked==true,是否可以在每次不测试的情况下暂停(在for loop of Work()中)? 测试“阻塞”变量也需要锁定,我认为这很耗时 class MyClass { AutoResetEvent wait_handle = new AutoResetEvent(); bool blocked = false; void Start()

在这段代码中,我想使用AutoResetEvent和bool变量暂停/恢复线程。 如果blocked==true,是否可以在每次不测试的情况下暂停(在for loop of Work()中)? 测试“阻塞”变量也需要锁定,我认为这很耗时

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);
            }
        }
    }
class-MyClass
{
AutoResetEvent wait_handle=新的AutoResetEvent();
布尔阻塞=假;
void Start()
{
螺纹=新螺纹(工件);
thread.Start();
}
无效暂停()
{
阻塞=真;
}
作废简历()
{
阻塞=错误;
wait_handle.Set();
}
私人工作()
{
对于(int i=0;i<1000000;i++)
{
如果(阻止)
等等;
控制台写入线(i);
}
}
}

是的,您可以使用
手动重置事件来避免正在执行的测试

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);
        }
    }
}
class-MyClass
{  
//将重置事件设置为最初发出信号,从而允许工作直到调用暂停。
ManualResetEvent wait_handle=新的ManualResetEvent(真);
void Start()
{
螺纹=新螺纹(工件);
thread.Start();
}
无效暂停()
{
等待句柄。重置();
}
作废简历()
{
wait_handle.Set();
}
私人工作()
{
对于(int i=0;i<1000000;i++)
{
//只要设置了这个等待句柄,这个循环就会执行。
//一旦重置,循环将停止执行并在此阻塞。
等等;
控制台写入线(i);
}
}
}