Reputation: 9445
I am trying to figure out how to separate the UDPClient receive callback from the processing of the received message. Due to the high volume of UDP messages coming in, we want to shift the actual processing of the message to another thread, hoping to take the weight off the UDP Client and not miss any of the incoming messages. (200 messages / second)
Does the AsyncCallBack occur on the same thread the UDPClient is on or a new thread? If it is on the same thread, then if I create a new thread inside the callback, I would be creating a separate thread per message which wouldn’t work. If the AsyncCallback is on the same thread as the connection, then my thinking is I would have to somehow create a thread prior to making the connection, then invoke something on that thread for each message received?
Private Sub OpenConnection()
_ipendpoint = New IPEndPoint(IPAddress.Any, _configobj.port)
_udpclient = New UdpClient(_ipendpoint)
_udpclient.BeginReceive(New AsyncCallback(AddressOf ReceiveCallback), Nothing)
End Sub
Private Sub ReceiveCallback(ar As IAsyncResult)
Dim bytes As Byte() = _udpclient.EndReceive(ar, _ipendpoint)
_udpclient.BeginReceive(New AsyncCallback(AddressOf ReceiveCallback), Nothing)
ProcessReceived(bytes)
End Sub
Private Sub ProcessReceived(bytes() As Byte)
Dim rcv As String = Encoding.ASCII.GetString(bytes).Trim()
'PROCESS MESSAGE ON DIFFERENT THREAD
End Sub
Upvotes: 1
Views: 262
Reputation: 171226
You're over-complicating things a bit. 200 messages per second is nothing.
First of all you need a reading loop:
while (true) {
var result = udpClient.Receive(...);
Task.Run(() => ProcessPacketAsync(result));
}
This is all it takes. You need to implement ProcessPacketAsync
. Depending on what that function does you need to make it use async IO. Often, synchronous IO is enough. The main reason to use async IO is to save threads when there is a great amount of concurrent operations.
You asked what threads these things run on. This does not matter but the answer is: On some thread pool thread.
Upvotes: 1