我正在开发一个Windows服务,它执行若干操作,包括侦听多个不同端口上的传入串行端口消息。如何在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)
//{
//}
}
没有必要使用一个线程,当你有一个“DataReceived”事件。请不要使用该事件并调用常规阻止Read()或不要使用线程。并且观察服务中对OnStart/OnStop的需求,您总是需要一个AutoResetEvent来检测服务应该暂停还是停止。你可以调用它的WaitOne()方法来阻塞线程。 –
@Hans说什么。您不必让程序在服务的OnStart()方法中运行,事实上,您应该尽快从中返回。您的程序将继续运行,直到服务停止。 – CodeCaster