The data received handler is executed in another thread. That is why you have to use
Invoke
to update the content of your text box from.
Similar applies to the
DataToSetandGet
variable used there to store the received string. You can't use it from other threads (like the GUI / main thread as in your
GLPBtn_Click()
function) without ensuring that only one thread accesses it at the same time.
You are also calling
serialPortForApp.ReadExisting()
in the above function and the received handler. That won't work too. Ask yourself: Which of the two read calls is executed?
The solution is to have only one function reading from the serial port. That is usually the received handler. If you have to access the received string from another thread, you have to use a shared variable and access it with appropriate locking mechanisms. The simplest solution would be writing a function that gets the received string as parameter and is called using
Invoke()
from the received handler. From within that function you can then update your text box and use the data for other purposes as well.
One technique to handle requests specific to a before send command is implementing a
Finite-state machine - Wikipedia[
^]. A simple example:
- State is idle (can send command)
- Sending a command: State is waiting for response (optionally a specific response)
- Answer received: State is has answer
- Answer processed: State is idle (can send next command)
Finally, there is no need to call
Sleep()
in a properly written multi threaded application. It should be avoided at all.