首页 > 解决方案 > In .NET, is it appropriate to invoke BeginSendTo in the callback?

问题描述

I'm using the .NET Socket interface with BeginSendTo(). In my callback that I pass to that function, I call EndSendTo() and then call BeginSendTo() from within that callback. Is that OK to do? I don't seem to find this type of implementation in the examples I see.

/// <summary>
/// The message queue in which incoming log messages are placed. These are emptied
/// during appropriate socket callbacks
/// </summary>
private readonly ConcurrentQueue<Message> MessageQueue = new ConcurrentQueue<Message>();

/// <summary>
/// The message sent callback. Calls EndSendTo on the socket and continues processing the
/// message queue.
/// </summary>
/// <param name="ar">The AsyncResult</param>
private void MessageSent(IAsyncResult ar)
{
  var bytesSent = Socket.EndSendTo(ar);
  SendFromMessageQueue();
}

/// <summary>
/// Begins sending the message on the socket
/// </summary>
/// <param name="message">The message to send</param>
private void BeginSendMessageOnSocket(Message message)
{
  var data = BinarySerialize(message);
  Socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, RemoteEndPoint, this.MessageSent,
    message);
}

/// <summary>
/// Starts sending messages from the message queue
/// </summary>
private void SendFromMessageQueue()
{
  while (MessageQueue.TryDequeue(out var message))
  {
    BeginSendMessageOnSocket(message);
  }
}

标签: c#.netsockets

解决方案


Yes, this is fine to do. All the examples I can find are based on TCP so they use BeginSend() and EndSend(). But the same callback principles apply and so BeginSendTo() and EndSendTo() can be used in the same way.

They both use the IOCP thread pool to do the IO.


推荐阅读