I am designing an application which communicates with another device via a serial port.
My application buffers the received binary data until the data is valid/of known format, does some processing and then writes back a response. I understand this model is known as the consumer/producer model. The issue I am having with properly implementing this model is that the message processing part of my application is fairly complex and involves calls to other classes/methods, etc., and when spawning a new thread I can only pass it one function. How can I best implement this?

Thank you for any help you can provide.

Paste sample code. You can do as much as you would like to in another thread. However BE WARNED you should _copy_ any byte[] buffers sent/received to any socket / serial ports. The memory is pinned by the CLR and modifying it will lead to rare but incredibly hard to diagnose bugs.

Simply have a receiving buffer (memory stream, expanding array, etc) and each time the serial port returns data append it to your rx buffer then send it off to parsing libs.

Paste sample code. You can do as much as you would like to in another thread. However BE WARNED you should _copy_ any byte[] buffers sent/received to any socket / serial ports. The memory is pinned by the CLR and modifying it will lead to rare but incredibly hard to diagnose bugs.

Simply have a receiving buffer (memory stream, expanding array, etc) and each time the serial port returns data append it to your rx buffer then send it off to parsing libs.

Thank you. I actually ended up using a modified version of the following model (for anyone else interested):

http://www.randomskunk.com/2011/02/generic-producer-consumer-class-in-c.html

Though I have been told that copying byte array is inefficient, my original implementation was done that way and so the only issues I had were threading related.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.