1

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);
}
4

1 回答 1

2

阅读回复后,您需要自己匹配它。

这是 UDP 的基本限制,而不是async/的限制await

如果您需要保持消息井井有条,我建议使用 TCP。TCP 就是为此而设计的。

于 2012-06-23T13:31:35.570 回答