0

i want to create a protocol, for a communication between my computer and a microcontroller. The first thing I want to do is to send the size of the data. This is already working, so my Serial Connection is already working. After i sent the size of the data, the microcontroller should allocate some memory and send an acknowledge byte, so the computer program knows that he is ready for the actual Data. For receiving the byte on my Computer, i am using a Handler:

private void DataReceivedHandler(
                    object sender,
                    SerialDataReceivedEventArgs e)

Now the problem is, that i don't know how I get the received Data (acknowledge byte) from the Handler to my function, so I can continue with my communication and send the actual Data to the microcontroller.

Is it possible, to wait in a function until a Handler will be executed and then jump back to the function and use the data which was received in the Handler?

Thank you very much

Roman R.
  • 68,205
  • 6
  • 94
  • 158
j.demi
  • 1
  • 1
  • Create a thread and block it using your [preferred signaling method](http://www.albahari.com/threading/part2.aspx#_Signaling_with_Event_Wait_Handles). Also consider to use timeout and cancellation. – Sinatr Jan 18 '18 at 14:32
  • Thank you very much for the awesome source. I created a thread now and used the signaling with the AutoResetEvent. Now I can wait in the Thread until the handler is executed. My question now is: How can I get the Information I receive from the Handler to the Thread I'm executing? – j.demi Jan 18 '18 at 15:37
  • Pass *information* via something what is accessible for both methods, use `static` variable as a starter (google [can answer](https://stackoverflow.com/q/35372766/1997232) your questions too). If problem still - you can ask *another* question. One more thing, if you find a solution what may be useful to someone else - consider to post it as an answer, you may get a valuable feedback as a payoff. – Sinatr Jan 18 '18 at 15:52
  • The DataReceived event was meant to be helpful in cases where you *don't* want to wait for a response. Somewhat important, serial ports are slow. But if you *want* to wait then it doesn't help at all, it significantly complicates the code. So don't use the event, just call Read() directly. – Hans Passant Jan 18 '18 at 17:42
  • What you really need is separate threads, a state machine, and delegates (callbacks). I wrote a decent example here: https://stackoverflow.com/a/38536373/2009197 – Baddack Jan 18 '18 at 18:19
  • You should ignore all of the above, and use `async`. How, specifically, to do this depends on the rest of your code. But, the usual approach is to read from the `SerialPort.BaseStream` object, which provides methods like `ReadAsync()`, which you can await. – Peter Duniho Jan 18 '18 at 19:25

0 Answers0