Search code examples
c#multithreadingmodbusplc

What should be the approach for writing polling service in c# for devices with varying interval


I have close to 400 PLC devices with Modbus interface which I want to poll and store the result in MySQL database. User will configure the polling interval for each device, say Temperature polling at 500 ms, Triangular waves at 1000 ms, Environmental parameters at 5000 ms, etc. I have stored all these information in database.

Now I want to write a windows service, which will do following:

  1. Read the communication parameters for each device from the database, e.g., IP address, register address, register count, etc.
  2. Initiate a thread for each device with specific interval
  3. That thread will keep polling the device and write the value in database, until the service is stopped.

Now, my question is how to implement separate thread for each device with its specific interval.

I'm using C# with nModbus library.


Solution

  • There are plenty of resources on how to poll on an interval. C# 4.0 - Threads on an Interval You could enumerate over a collection of configured timer intervals and spin of a thread for each.

    With that many concurrent threads I would suggest queuing these. Whether you use a queue product such as MSMQ or custom roll some sort of thread safe concurrent dictionary to handling the queuing. Here's one resource on custom queuing: http://www.nullskull.com/a/1464/producerconsumer-queue-and-blockingcollection-in-c-40.aspx

    Hopefully, this will get you going in the right direction.