You should look at other communication models for transmission / reception, for example HTTP. In .NET, the HTTPWebRequest object is where you collect all the pieces of information that should be sent over the wire, including the command (HTTP METHOD: GET, PUT, POST, etc.) and a stream of bytes. The HTTPWebRequest object (and the HTTP stack) internally deals with the โworkflowโ of computing checksums of data, breaking big data into smaller packets, etc. All your code needs to do is build a request object, set a command, assign a data stream to the property of the request object, and send.
Another reason you should look for existing models of communication objects, such as .NET HTTP, is that serial communications are usually asynchronous from the perspective of your CPU. While transmitting request characters to the serial port and while waiting for a response, a lot of processor time may elapse. Use an asynchronous model for your request / response so as not to block the calling thread and potentially freeze your user interface.
To continue the .NET HTTP example, HTTPWebRequest has a GetResponse method that sends a request and blocks the calling thread until a response is received. HTTPWebRequest also has a pair of BeginGetResponse () / EndGetResponse () so you can send a request and provide a callback that will be executed when the response arrives soon.
Even if your direct design is in order with a synchronous call model with thread blocking, you should at least investigate asynchronous coding patterns and consider implementing your object as such. You can always call an asynchronous method synchronously with blocking threads, but it is much more difficult to call a synchronous method asynchronously. Invest a little time to give yourself more opportunities in the future.
source share