Я пытаюсь воспользоваться новыми конструкциями async/await при работе с UdpClient. У него есть несколько асинхронных методов, которые хорошо работают с async/await.
Проблема возникает, когда мне нужно связать текущий запрос с соответствующим ответом. Поскольку ответы от UdpClient не упорядочены, можно испортить всю логику, используя:
var response = await udpClient.ReceiveAsync();
// We might receive here a response
// that belongs to other request
Полный источник ниже:
// 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);
}