如何在c#中结束中断线程
本文关键字:结束 中断 线程 | 更新日期: 2023-09-27 17:49:18
我正在使用Netduino板,我在结束NativeEventHandler(按钮)时遇到了问题。问题是主线程卡在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.
}
}
首先,当您订阅一个事件时,您将保持订阅状态,直到您取消订阅。所以你只需要订阅一次。
我相信你可以像这样做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或任何你想做的