Search code examples
c#eventsdesign-patternsmicrocontrollerftdi

Best Practices? Wait until receive or raise an event on receive


First of all, I wanted to thank the community. You've been of great support lately ! Usually i don't even need to ask the questions because they're already there. Now i have an issue that's not directly related to code but programming itself.

I'm working with a FTDI Chip and C# programming a communication protocol in which a PC application acts like the Master (will send requests) and there is also Slave device who will answer to them, not immediately, maybe a couple of millisecs, but anyway, will take some time. I'm stuck in a conceptual/philosophical code design question.

After sending a request, should I ask right away for an answer (checking also a timeout) or should I constantly monitor the input (BackgroundWorker powered) and raise an event after receiving a data input ? What would you recommend, what is on your experience. What factors should i consider for making my choice ?

I never studied software design of programming itself so i think i lack the basic on this, but this is a personal project i'm working on and sure i'd love some feedback/pointers on this from you guys.

Thanks !


Solution

  • My preferred solution in this scenario would be to issue the request in async mode (such that you get called back by an event that fires when it completes), and also implement an async time out using standard .Net mechanisms, which calls you back if it appears the slave is unresponsive. This way you just start the request and the timer and then can continue doing more work, without needing any other threads to process results.

    You would have to make sure that concurrent time out and response arrival is handled cleanly using a locking mechanism, so that you know for sure whether you are timing out or handling the response.

    Try to avoid polling and input monitoring, unless your slave's API does not allow for deterministic generation of response events.