How can C use lambda to hook a delegate event

  • 2020-05-17 06:14:56
  • OfStack

Delegation is defined as follows:


public class SocketSp
{
 public delegate void ReceiveCompleted(byte[] receiveBuffer, int receiveTotalLen,Exception ex);
 public ReceiveCompleted receiveCompleted;
}

The hook party is defined as follows

public class LinkOuter
{
 SocketSp linkOuterSocket = new SocketSp();

       private void test(Socket requestHandleSocket)
      {
           // This is where you hook up   linkOuterSocket.receiveCompleted  The event will also want to take parameters requestHandleSocket Pass in for subsequent processing. 
      }
}

The first idea was to take advantage of delegate, but it failed. Because although it is hooked up, the parameters passed in by the delegate are lost, and subsequent operations cannot be carried out.

private void test(Socket requestHandleSocket)
{ 
linkOuterSocket.receiveCompleted += delegate {
//To do
};
}

The second idea, using Action, also failed. IDE indicates that the delegate Action does not take three parameters.

private void test(Socket requestHandleSocket)
{
linkOuterSocket.receiveCompleted += (Action)((outerReceiveBuffer, totalLen, ex) => { 
//To do
});
}

The third idea is to use the lambda expression to hook up with the delegate first, and at the same time to use the call of local variables to pass the parameters into the sendResponse function for subsequent operations.

private void test(Socket requestHandleSocket)
{
linkOuterSocket.receiveCompleted += new SocketSp.ReceiveCompleted((outerReceiveBuffer,totalLen,ex) =>
{ 
byte[] realOuterReceiveBuffer = new byte[totalLen]; 
Array.Copy(outerReceiveBuffer, 0, realOuterReceiveBuffer, 0, totalLen); 
sendResponse(requestHandleSocket, realOuterReceiveBuffer,"200 OK", "text/html");
});
}

Finally, it was implemented using the lambda expression.


Related articles: