Note. I edited this question to help other people with the same problem get help here. To see the original question that is best for some answers, check the change history.
In the project, I have an ExecutionManager class that can contain multiple instances of ExecutionSlot. The ExecutionSlot class has several public event fields, such as:
public event EventHandlers.ObjectEventHandler<IPlugin> ExecuteCompleted;
For each of these events, there is a matching event in the ExecutionManager. The desired behavior is that every time an ExecutionSlot is executed, an event occurs, the corresponding event also occurs in the containing ExecutionManager.
An example solution was that whenever an ExecutionSlot was added to the ExecutionManager, the ExectionManager would add its own events to the ExecutionSlot as follows:
executionSlot.ExecuteCompleted += ExecuteCompleted;
There is no need to delete ExecutionSlot, so events are never deleted.
The problem is that the event in the ExecutionManager is not raised. After confirming that the event was viewed using ExecutionSlot, I found that changing the above line to the following was fixed:
executionSlot.ExecuteCompleted += (sender, eventArgs) => ExecuteCompleted(sender, eventArgs);
And I could not understand why, so my question was, what is the difference.
The reason for this difference was that the former adds current ExecutionManager event listeners to the ExecutionSlot event. Therefore, any listeners added later will not be called when the event is raised. In contrast, the latter solution uses a lambda to raise an ExecutionManager event, which means listeners will be called during the event.
The main reason for the failure of the first decision is that delegates are immutable. Therefore, when you add a new delegate and event, you actually create a new delegate that contains the existing delegates and the added one. Therefore, any reference to delegates that were made earlier will not contain the newly added delegate.