I’m attaching action like that in constructor:
model.DataArrived += new Action<List<ConsoleData>>(model_DataArrived);
Should I detach it in OnDispose? Is it ok to create a new instance like that?
protected override void OnDispose()
{
model.DataArrived -= new Action<List<ConsoleData>>(model_DataArrived);
Or I should detach exactly the same instance that I’ve created in constructor? Should I keep this instance in private field only for detaching purposes?
That is fine.
Delegates are compared by value, not by reference.
The
Delegate.Removemethod, and the corresponding-operator, remove the last matching delegate from the first operand.You only need to remove the handler at all if
modelwill live longer than your object. If so, the event inmodelwill keep a reference to your object, keeping your object alive for too long.