Snippet - Wait for an Event or Timeout, Whichever Comes First

Wait for an Event or Timeout, Whichever Comes First

Simple helper class that allows the user to pause thread execution until some condition is met, with an optional timeout.

Sorry, I don’t understand the use of your class. What is wrong with the default .NET implementation, like this:


public class Program
    {
 
        private static ManualResetEvent WaitObj = new ManualResetEvent(false);
 
        public static void Main()
        {
            // The LDR button is used to cancel the wait operation in this example.
            InterruptPort myInterruptPort = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.LDR, false, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLow);
            myInterruptPort.OnInterrupt += new NativeEventHandler(myInterruptPort_OnInterrupt);
 
            while (true)
            {
                Thread.Sleep(1000);

               WaitObj.Reset();

                Debug.Print("You have 5 seconds to press the LDR button.");
 
                if (!WaitObj.WaitOne(5000, false))
                    Debug.Print("TIMED OUT!");
                else
                    Debug.Print("BUTTON PRESSED!");
            }
        }
 
        // Interrupt handler that cancels the wait operation.
        static void myInterruptPort_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            WaitObj.Set();
        }
 
    }

Sorry for the extremely late reply. I didn’t realize Codeshare had a submission discussion feature until now.

Yes, you’re right! If I had known that particular overload of the WaitOne() method existed in the micro framework, I would not have had to go through the trouble of rolling my own implementation. Doh! Somehow I thought that overload existed in the full framework but was omitted in NETMF. Looks I was wrong.

Thanks for your comment. The built-in method is much more efficient!