Hi,
I am sending commands to some server via an UdpClient. However, I need to make sure that all commands send are separated by a 1 second delay. If there is no delay, two commands send within this 1 second timespan will not be received both; only the first or the second command will get through.
The commands are sent in a background thread at the moment, because it might take some time before the command is sent. I keep looping until the command has been sent, like this:
vb.net Code:
Public Sub Send(command As String) Dim bytes = Me.GetCommandBytes(command) Dim t As New Thread(ThreadSend) t.Start(bytes) End Sub Private Sub ThreadSend(commandBytes As Object) Dim bytes = DirectCast(commandBytes, Byte()) Dim sent = False While Not sent Me.Client.Send(bytes, bytes.Length, _IpEndPoint) Thread.Sleep(200) If Me.Client.Available > 0 Then sent = True End If End While End Sub
This does not keep into mind the 1 second delay though. When I send four commands consecutively, like:
The results seem a little random, but I never get them all. Sometimes just 1, sometimes 1 and 3, sometimes 2 and 3, sometimes even 4 and then 1Code:Send("test1") Send("test2") Send("test3") Send("test4")
I have reason to believe that the 1 second delay will fix this (if not, well, then I'm clueless, but I'm sure you are as well so there's no point in asking).
I'm not sure how to build this delay however. Simply adding a Thread.Sleep(1000) in the ThreadSend method won't work of course; the four commands sent consecutively will all wait one second and then still be sent (nearly) at the same time. There needs to be a delay between commands, not before commands.
I am thinking I need some kind of Queue which I fill with the commands in the Send method. Then another thread is constantly looping through this Queue, in one second intervals, and sending the first command (if one is available).
However, I have a feeling something like this should be easier. I have heard about the ThreadPool before, which sounds like it might do what I want already, but I have no clue how to use it. The thing is: the ThreadPool seems to fire off as many threads as it can before it queues up new threads; and it handles those new threads as soon as they are available, which is not what I want at all.
Any ideas?



Reply With Quote
