Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...