3

我正在使用 Netduino 板,但在结束 NativeEventHandler(button) 时遇到问题。问题是主线程卡在 join() 函数上。我不明白为什么子线程在运行后没有被释放。

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.
    }
}
4

1 回答 1

4

首先,当您订阅一个事件时,您会一直保持订阅状态,直到您取消订阅。所以你只需要订阅一次。

我相信你可以像这样做netduino......

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 ...
    }
}

所以基本上,无论你想在按下按钮时发生什么,都可以在 ButtonEvent 中执行

我认为你不需要做任何其他事情。

这:

Thread.Sleep(Timeout.Infinite);

只是用来保持程序运行。

所以在......在这里做任何事情......你可以闪烁你的LED或任何你想做的事情。

于 2012-12-20T23:43:32.827 回答