我正在编写一个 C# windows 服务来不断地从 4 个不同的硬件设备读取数据。 loops/sleeping 的定时器或线程?

I'm writing a C# windows service to constantly read from 4 different hardware devices. Timers or threads with loops/sleeping?

我正在后台为 运行 编写 Windows 服务,并读取(通过提供的 C# sdk)4 个独立的 USB 摄像头模块的数据,这些模块通过硬件在外部触发。我想制作相对模块化的部件,这样我们就可以轻松地使用更多或更少的相机模块。因此,我可能会制作一个 "camera reader" class 并在服务上下文中根据需要创建尽可能多的内容。为了时间的缘故,我还需要一个单独的实体来将收集到的所有图像写入磁盘。

我以前没有开发过 Windows 服务或编写过 C#,我的问题是:class 包含计时器对象和滴答函数之间有什么真正的区别而不是让 class 启动一个循环检查相机并计算睡眠时间以定期进行的线程? Windows 我一直发现的服务示例都使用计时器来执行正在进行的后台任务。

我对写入磁盘的实体有同样的问题。这也可能是另一个计时器或线程,尽管我倾向于那里的线程,因为我有一个带有信号量的队列,可以从中提取它的工作。

这两种方式都可以正常工作(只要您不使用 System.Windows.Forms.Timer,它需要一个消息循环才能工作)。

这就是MSDN关于定时器的说法:

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Windows.Forms.Timer, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

  • System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

所以,使用任何能让你的船漂浮的东西!

至于将数据写入磁盘,有一个专用线程保持队列并一次写入一个文件对我来说听起来不错!