how to use event to re-write this code segment?

This is a discussion on how to use event to re-write this code segment? within the C# Programming forums, part of the General Programming Boards category; Hello everyone, Here is my code segment for a thread, which will sleep one second, do some work and check ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    how to use event to re-write this code segment?

    Hello everyone,


    Here is my code segment for a thread, which will sleep one second, do some work and check if the stop status is set -- if set, then break the loop and stops the method.

    My question is, whether it is possible to use event (e.g. ManualResetEvent) to implement similar logics?

    Code:
            void ThreadMethod1()
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    if (stop)
                    {
                        // break;
                    }
                    else
                    {
                        // do something
                    }
                }
            }

    thanks in advance,
    George

  2. #2
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    Yes. Instead of Sleep you could "Wait" for your event with a timeout of 1000. The wait function will return whether it timed out or the event was set. If it timed out, run your code and wait again, if it was set, leave the loop.

    In your other code, instead of a stop variable, set the event. As with a normal variable, you need to reset the event after your loop ends. If this is the only portion of code "Wait"-ing for this event, you can use an AutoResetEvent, which will reset itself automatically after being waited for.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need the code of few programs in c++.plzzzzz help...plzzz
    By NAVINKR20 in forum C++ Programming
    Replies: 1
    Last Post: 05-08-2009, 09:13 AM
  2. True ASM vs. Fake ASM ????
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 04-02-2003, 03:28 AM
  3. How do I write more efficient code?
    By minesweeper in forum C++ Programming
    Replies: 4
    Last Post: 08-06-2002, 11:08 AM
  4. How to write code to change the printer resolution
    By ooosawaddee3 in forum C++ Programming
    Replies: 0
    Last Post: 07-26-2002, 06:04 PM
  5. << !! Posting Code? Read this First !! >>
    By biosx in forum C++ Programming
    Replies: 1
    Last Post: 03-20-2002, 11:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21