.net中新的异步/等待构造导致颠簸

时间:2012-06-23 11:34:50

标签: c# .net asynchronous .net-4.5

我正在尝试在使用UdpClient时利用新的async / await结构。它有几个异步方法,可以与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);
}

1 个答案:

答案 0 :(得分:2)

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

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

如果您需要按顺序保留邮件,我建议使用TCP。 TCP就是为此而设计的。