Question

I am using UdpClient (c++/cli), I start my listener using the obvious BeginReceive.

System::Void CUdpTransmitter::StartListener() {
  ...
  m_UdpClient->BeginReceive ( gcnew System::AsyncCallback(ReceiveCallback), this );
}

ReceiveCallback should start new AsyncCallback at the end. Is there any performance benefit or any other reason to store the AsyncCallback in a member variable, rather than allocate a new one on each call? What about thread safety? Compare following variants:

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 );
    }
  }
}

Thanks for your time and your answers.

Was it helpful?

Solution

Delegates are thread safe, so there's no worry about that. (Delegates are immutable after creation, any method that adds or removes a delegate from a multicast delegate is actually returning a new multicast delegate.)

There's a very minor performance penalty for instantiating the delegate objects and garbage collecting them, so if you're using this delegate very frequently, then go with m_callback. However, as I said, this is a very minor penalty unless you're doing it several million times per second.

If you're not doing this frequently, and you want to clean up your code and have less class members hanging around, go ahead and instantiate the callback each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top