Search code examples
c#multithreadingnetduino

How to end an interrupting thread in C#


I'm using a Netduino board and I'm having a problem with ending a NativeEventHandler(button). The problem is main thread stuck at the join() function. I dont understand why the childthread is not released after it is run.

public class Program
{
    private static Thread mainThread;
    private static Thread childThread;     

    private static InterruptPort button = new InterruptPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLevelHigh);

    private static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

    public static void Main()
    {            
        mainThread = Thread.CurrentThread;
        Thread.Sleep(1000);
        while (true)
        {
            Thread.Sleep(100);
            button.OnInterrupt += new NativeEventHandler(ButtonEvent);
            mainThread.Suspend();
            childThread.Join();//It stuck here.
            Thread.Sleep(100);
            button.EnableInterrupt();
            button.ClearInterrupt();  
        }
    }

    private static void ButtonEvent(uint port, uint state, DateTime time)
    {
        childThread = Thread.CurrentThread;
        button.DisableInterrupt();          
        mainThread.Resume();
       // Thread.CurrentThread.Abort(); this .Abort() seems doesn't terminate the thread either.
    }
}

Solution

  • First of all, when you subscribe to an event, you stay subscribed until you unsubscribe. So you only need to subscribe once.

    I believe you can do the netduino like this...

    public class Program
    {
        private static InterruptPort button = new InterruptPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLevelHigh);
    
        private static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
    
        public static void Main()
        {            
            button.OnInterrupt += new NativeEventHandler(ButtonEvent);
            Thread.Sleep(Timeout.Infinite);
        }
    
        private static void ButtonEvent(uint port, uint state, DateTime time)
        {
            ... do whatever here ...
        }
    }
    

    So basically, whatever you want to happen when the button is pressed, do in the ButtonEvent

    I don't think you need to do anything else beyond that.

    The:

    Thread.Sleep(Timeout.Infinite);
    

    simply serves to keep the program running.

    So in the ... do whatever here ... you could flash your LED or whatever you want to do.