Lu4
Lu4

Reputation: 15032

New async/await constructs in .net cause bumps

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

Upvotes: 1

Views: 848

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457127

You need to match it up yourself after reading the response.

This is a fundamental limitation of UDP, not a limitation of async/await.

If you need to keep your messages in order, I recommend TCP. TCP was designed for that.

Upvotes: 2

Related Questions