|
-
Nov 4th, 2011, 03:24 PM
#1
Thread Starter
Addicted Member
Re: Timer delay
 Originally Posted by Shaggy Hiker
Sorry, a series of things got posted while I was frothing over that busy wait.
The proper solution is not quite as easy to show, because it involves a conceptual shift. The proper way to do this is to add a timer component to your form. Set the interval of that timer to 4000 (because the interval is in milliseconds, so 4000 milliseconds would be 4 seconds). Double click on the timer to go to the timer tick event handler. In that handler is where the serialport Send operation should be located.
The other part is setting up the things to send. I don't know what those packets are, but I would guess that they are arrays of bytes. Therefore, add a Queue (of Byte()) at form scope. Wherever you are currently doing the sending, change the code so that you are enqueueing each packet rather than sending them. Once you have enqueued all your packets you can start the timer.
What is happening in the timer tick is that it checks the queue to see that the count > 0. If it is, dequeue the next item and send it. Once the count = 0, stop the timer.
That's the way to do it in a single thread. DB has a solution that would send all of those items in a background thread, which has certain advantages, but might be more difficult to implement if you aren't familiar with threads. Either way, the queue is a good idea. In fact, you could just leave the timer running and whenever you enqueue something, it will be sent when the timer gets to it.
In the following code, I enqueue SendQueue. After I added the first array, I updated SendBuffer() and tried to add one more object into SendQueue. However, the first one was changed to the same as the second. Do I have to declare another array to store the object first before I add it into SendQueue?
Public SendQueue As Queue(Of Byte()) = New Queue(Of Byte())()
Private Sub ReadSNButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReadSNButton.Click
Dim SendBuffer() As Byte = New Byte() {0}
Array.Resize(SendBuffer, 20)
BytesSent = 5
SendBuffer(0) = &H43
SendBuffer(3) = READ_SERIAL_NUM_L
SendBuffer(4) = CalCheckSum(SendBuffer, BytesSent - 2) 'checksum
SequenceRunning = False 'regular message instead of sequence
SendQueue.Enqueue(SendBuffer)
BytesSent = 5
SendBuffer(0) = &H44 'format
SendBuffer(3) = READ_SERIAL_NUM_H
SendBuffer(4) = CalCheckSum(SendBuffer, BytesSent - 2) 'checksum
SendQueue.Enqueue(SendBuffer)
End Sub
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|