Reputation: 89
I'm developing ASP .Net core application to communicate with USB Serial device to read/write device information using binary serializer.
Moreover, I have created a common wrapper project to communicate with hardware using SerialPortStream and BinarySerializer. There is a method to accept the command from user and serialize and deserialize the command and finally return the output. Method name -IGenericMessagePacket GetMessageFromDevice(IGenericMessagePacket packet).
So as per requirement, I have to create a long running task to communicate with device in every 1sec to get current status of the device. In between, there is another method will be called by user to get another information from device.
Long running task and general function are trying to communicate with device. I'm getting irrelevant output when handling above scenarios. I used lock but it will make some problem.
can anyone suggest me how to solve this issue?
Upvotes: 0
Views: 53
Reputation: 36629
A typical solution would be a task queue that ensures that all access to the device is done sequentially.
You could use something like a LimitedconCurrencyTaskScheduler. So you would create a single taskscheduler that is shared between all components, and all access to the device would be done by starting a task with this task scheduler, including for your reoccurring work. This has the minor advantage that no thread would be used when the device is idle.
You could also create a simple task scheduler yourself. A simple one would be use a blocking collection store the work to be done, and a long running thread that iterates over the collection using GetConsumingEnumerable
.
There are also libraries like DataFlow or Rx.net that might help, but I have little experience with these, so I cannot provide any concrete recommendations.
Upvotes: 0