C# .net中的新异步/等待构造会导致碰撞
我试图在使用UdpClient时利用新的async/await构造。它有几个异步方法,可以很好地处理async/await 当我需要将当前请求与适当的响应连接起来时,就会出现问题。由于UdpClient的响应不按顺序排列,因此可以使用以下命令打乱整个逻辑:C# .net中的新异步/等待构造会导致碰撞,c#,.net,asynchronous,.net-4.5,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 完整资料
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);
}
//这里我试图提供统一的消息发送逻辑
专用异步任务SendMessageAsync(IPEndPoint目标,消息消息)
{
var stream=newmemoryStream();
序列化(流、消息);
var buffer=stream.GetBuffer();
//我在这里发信息
var numBytes=await udp.SendAsync(buffer,buffer.Length,destination);
//现在我需要等待回应
//但我不能只使用:
//var response=await udp.ReceiveAsync();
//因为当前的接收操作可能捕获受影响的数据
//另一个发送消息操作已在
//当前的一个。
//那么,问题是如何实现以下构造:
//return wait GetResponse(message.ConversationID);
}
阅读响应后,您需要自己进行匹配
这是UDP的基本限制,而不是async
/wait
的限制
如果您需要保持消息的有序,我建议使用TCP。TCP就是为此而设计的