c# - 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);
}
}
解决方案
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.
推荐阅读
- amazon-web-services - 从其他账户登录 Cognito 后访问 S3 存储桶
- cluster-analysis - sklearn python 亲和传播 - 有没有一种方法来计算集群中的错误?
- python - Python,浮点记录文本文件,加载浮点数并平均它们
- javascript - 如何翻译用 javascript 生成的文本
- c# - Visual Studio 调试旧版本的代码 - 仅用于实例化类
- javascript - Google Map API 密钥问题 Javascript
- java - 如何限制在 Firestore 中添加和删除侦听器的数量?
- c++ - 尝试实现工厂模式时如何修复“分段错误(核心转储)”
- xaml - 如何在初始屏幕 Xamarin 中删除额外的 NavigationBar
- kendo-ui-angular2 - 没有图例的图表区域的剑道图表高度