Search code examples
c#.netmultithreadinguart

Threads using the same resource


I have C# multi threading program that using UART trough c++ COM object. I'm accessing UART from couple threads and it is not allowed.

My solutions:

  1. access to UART only from one thread and perform all other threads requests in the beginning of each cycle. The problem with this solution is that all other threads will wait a lot of time before receiving response.
  2. Create prioritized thread that only will access UART. The problem with this solution is that it is very risky.

What solution is the best and why? There is another solution?


Solution

  • I would suggest a dedicated thread that pulls requests from a ConcurrentQueue and operates on the UART. All other threads should Enqueue requests and continue on with their work, so there's no waiting involved. Does that fit your needs?

    Here's the documentation for ConcurrentQueue