Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

c# - Pause/Resume thread whith AutoResetEvent

In this code I want to Pause/Resume a thread using an AutoResetEvent and a bool variable. Is is possible to Pause whithout testing each time (in for loop of Work()) if blocked==true? Testing of "blocked" variable needs locking also and i think this is time consuming.

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);
            }
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...