Reputation:
I'm currently writing a program which involves sending and receiving messages via a Serial connection. For that purpose, I'm using events to handle the reception of messages(I've tried doing it without them, but I didn't find anything but problems, and I'm not sure if it is due to the sending messages part of the code or the reception of messages part) and a question arose. If I'm in a Console.ReadLine statement, in which I haven't written anything yet, and an event is received, would the event be received and handled or not? More precisely, what would happen in that situation?
Upvotes: 1
Views: 183
Reputation: 36649
read the documentation of the serial connection about what thread the events are raised on.
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.
Since it is received on a background thread it will run independently from your other threads, possibly concurrently with your readLine. So you will need to ensure that the code is threadsafe.
Upvotes: 1