C# 在成员变量中存储AsyncCallback相对于创建新变量的性能优势

C# 在成员变量中存储AsyncCallback相对于创建新变量的性能优势,c#,c++-cli,udpclient,asynccallback,C#,C++ Cli,Udpclient,Asynccallback,我正在使用UdpClient(c++/cli),我使用明显的BeginReceive启动我的侦听器 System::Void CUdpTransmitter::StartListener() { ... m_UdpClient->BeginReceive ( gcnew System::AsyncCallback(ReceiveCallback), this ); } ReceiveCallback应在末尾启动新的AsyncCallback。将AsyncCallback存储在成员

我正在使用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 );
    }
  }
}

感谢您的时间和回答。

代理是线程安全的,因此不必担心这一点。(委托在创建后是不可变的,任何从多播委托中添加或删除委托的方法实际上都会返回一个新的多播委托。)

实例化委托对象并对其进行垃圾收集会带来很小的性能损失,因此,如果您非常频繁地使用此委托,请使用m_回调。然而,正如我所说,这是一个很小的惩罚,除非你每秒做几百万次


如果您不经常这样做,并且希望清理代码,减少类成员的闲逛,请继续,每次都实例化回调

嗯,我正在分析来自6台摄像机的数据(VGA分辨率为30fps,灰度为8bit),考虑到MTU 1500字节,这意味着大约37000个数据包/秒。根据您的回答,似乎不值得存储m_回调。但无论如何,由于缺乏经验,我想知道,是否有可能以这种方式重用m_回调。谢谢你的回答。