I have a program for carrying out serial communication. After sending a command, the program has to wait for a short while to receive the data. The data is received using ActiveX MsComm
http://msdn.microsoft.com/en-us/library/aa259393%28v=vs.60%29.aspx
The psuedocode looks something like this:
timer_tick
send data (node 1)
sleep(500) 'receives data for node 1 meanwhile
send data (node 2)
. . .
the problem is that sleep causes the GUI to lag. I've thought of a few alternatives
1) using an artificial counter in the timer to approximate 500ms before sending the next command but does not seem like a very good idea to me 2) using a thread instead of a timer? and setting it as a background thread
http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground(v=vs.71).aspx
3) making use of application.doevents?
I am not so familiar with option 2 or 3, therefore i am hesitant to introduce possibly complicating elements into my code. Can anybody advise of any alternative that's better suited for this problem or to start working towards option 2 or 3?
The issue is the fact that your timer
is running on the UI thread, so when you sleep
in that sub-routine, you are sleeping the UI thread (hence the 'lag').
The best probably easiest to understand option is to add a BackgroundWorker
control to your form and move your sending (and sleep) code into the worker DoWork
routine, which will not block the UI thread.
Something like this:
Worker_DoWork
send data (node 1)
sleep(500) 'receives data for node 1 meanwhile
send data (node 2)
End Sub
The use of DoEvents
is strongly discouraged - there are very few reasons for using this in .NET