I am trying to take advantage of new async/await constructs while working UdpClient. It has several async methods that work nice with async/await.
The problem occurs when I need to connect current request with appropriate response. Since responses from UdpClient are not ordered, it is possible to mess up whole logic by using:
var response = await udpClient.ReceiveAsync();
// We might receive here a response
// that belongs to other request
Full source below:
// Here I am trying to provide unified message sending logic
private async Task<Response> SendMessageAsync(IPEndPoint destination, Message message)
{
var stream = new MemoryStream();
formatter.Serialize(stream, message);
var buffer = stream.GetBuffer();
// Here I am sending message
var numBytes = await udp.SendAsync(buffer, buffer.Length, destination);
// Now I need to wait for response
// but I can't just use:
// var response = await udp.ReceiveAsync();
// Because current receive operation might catch data that is subject to
// another send message operation which has started some time before the
// current one.
// So how the question how is it possible to implement the following construct:
// return await GetResponse(message.ConversationID);
}