我正在使用 UdpClient (c++/cli),我使用明显的 BeginReceive 启动我的监听器。
System::Void CUdpTransmitter::StartListener() {
...
m_UdpClient->BeginReceive ( gcnew System::AsyncCallback(ReceiveCallback), this );
}
ReceiveCallback 应该在最后开始新的 AsyncCallback。是否有任何性能优势或任何其他理由将 AsyncCallback 存储在成员变量中,而不是在每次调用时分配一个新的?线程安全呢?比较以下变体:
System::Void CUdpTransmitter::ReceiveCallback1( System::IAsyncResult ^ asyncResult ) {
m_UdpClient->EndReceive();
// parse received data (not time consumpting)
...
if (! exit) {
m_UdpClient->BeginReceive ( gcnew System::AsyncCallback(ReceiveCallback), self );
}
}
public ref class CUdpTransmitter {
AsyncCallback ^ m_callback; // store AsyncCallback in a member variable, it will be initized in constructor... gcnew System::AsyncCallback(ReceiveCallback2)
System::Void CUdpTransmitter::ReceiveCallback2( System::IAsyncResult ^ asyncResult ) {
m_UdpClient->EndReceive();
// parse received data (not time consumpting)
...
if (! exit) {
// start receiving, reuse the member variable and avoid gcnew
m_UdpClient->BeginReceive ( m_callback, self );
}
}
}
感谢您的时间和回答。