c# - 使用 AutoResetEvent 暂停/恢复线程

标签 c# .net multithreading

在这段代码中,我想使用 AutoResetEvent 和 bool 变量暂停/恢复线程。 如果 blocked==true 是否可以暂停而无需每次测试(在 Work() 的 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);
            }
        }
    }

最佳答案

是的,您可以使用 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);
        }
    }
}

关于c# - 使用 AutoResetEvent 暂停/恢复线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3228211/

相关文章:

c# - 使用 WCF 在另一个 CLR 地址空间中执行代码并返回对象

c# - 无法使 ASP.NET MVC 客户端验证工作

c# - 如何在 WPF 中创建自己的图形效果?

c# - 在 C# 中以无序序列重复和计数循环

c# - Unity - OnMouseDown 双击

c# - 如何将 MonoGame 安装到 Visual Studio 2013 中?

c# - “令人愉快的并行”PLINQ 查询

c# - 允许工作线程在主线程显示对话框时工作

java - 如何从 Eclipse 中的线程中提取堆栈跟踪?

java - 线程启动后服务器/客户端程序停止工作