如何在Windows服务中保持线程打开

时间:2015-02-04 20:20:14

标签: .net windows multithreading service

我正在开发一个Windows服务,可以执行多项操作,包括在几个不同的端口侦听传入的串行端口消息。

通过为每个串行设备打开一个线程来进行监听。

我仍然想知道如何在听的时候保持线程畅通。 我尝试了一些像while(true){}循环这样的东西,它可以工作,但在连接多个设备时将cpu设为100%。

在控制台应用程序中,我可以使用console.readline(),我正在寻找类似且简单的东西。

这就是我现在拥有的,我怎样才能让它发挥作用?

    public static void Start()
    {
        var devices = MyService.Kernel.Get<IDevicesService>();
        foreach (var device in devices.ComDevices.List())
        {
            var thread = new Thread(() => StartKeypadThread(device.Id));
            thread.Start();
        }
    }

    public static void StartKeypadThread(int deviceId)
    {
        var devices = MyService.Kernel.Get<IDevicesService>();
        var device = devices.ComDevices.Find(deviceId);
        var c = new SerialConnector(device);
        c.SerialDataRecieved += c_SerialDataRecieved;
        c.Start();
        //Console.ReadLine(); --> I know, sounds stupid, it's a Service :)
        //while (true)
        //{
        //}
    }

2 个答案:

答案 0 :(得分:0)

字面回答:Thread.Sleep(Timeout.Infinite)

为什么你需要“挂”线程,尤其是永远?也许您应该使用在您希望服务停止时发出信号的ManualResetEvent。

此外,不需要启动所有这些子线程来仅附加事件。每个都将运行1ms左右,然后退出。浪费时间。

答案 1 :(得分:0)

谢谢大家的帮助。 我没有线程经验,所以也许我确实不需要使用这些线程,但是当我没有使用时,我在服务的另一部分(我没有'我得到了一个错误“安全句柄已经关闭”使用这些Com设备。)

为了快速解决问题并继续使用这些线程,我使用WaitHandler找到了另一种解决方案。

如果有人需要,我就是这样做的:

public static void Start()
{
    var devices = MyService.Kernel.Get<IDevicesService>();
    foreach (var device in devices.ComDevices.List())
    {
        var thread = new Thread(() => StartKeypadThread(device.Id));
        thread.Start();
    }
}

public static void StartKeypadThread(int deviceId)
{
    var devices = MyService.Kernel.Get<IDevicesService>();
    var device = devices.ComDevices.Find(deviceId);
    var c = new SerialConnector(device);
    c.SerialDataRecieved += c_SerialDataRecieved;
    c.Start();
    var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, Guid.NewGuid().ToString());
    waitHandle.WaitOne();
}