【问题标题】:Pause/Resume thread whith AutoResetEvent使用 AutoResetEvent 暂停/恢复线程
【发布时间】:2010-07-12 11:48:49
【问题描述】:

在这段代码中,我想使用 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);
            }
        }
    }

【问题讨论】:

    标签: c# .net multithreading


    【解决方案1】:

    是的,您可以使用ManualResetEvent 来避免您正在执行的测试。

    ManualResetEvent 将让您的线程通过,只要它被“设置”(发出信号),但与您之前的@​​987654323@ 不同,它不会在线程通过它时自动重置。这意味着您可以将其设置为允许在循环中工作,并且可以将其重置为暂停:

    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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-21
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2010-12-28
      • 2020-08-13
      相关资源
      最近更新 更多