Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

should I detach action after attaching?

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?

Upvotes: 3

Views: 101

Answers (2)

SLaks
SLaks

Reputation: 887867

That is fine.
Delegates are compared by value, not by reference.

The Delegate.Remove method, and the corresponding - operator, remove the last matching delegate from the first operand.

You only need to remove the handler at all if model will live longer than your object. If so, the event in model will keep a reference to your object, keeping your object alive for too long.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273571

Should I detach it in OnDispose?

Yes. Otherwise the model instance would keep this instance from being collected.

And as Slaks answered, the -= notation is fine.

Upvotes: 1

Related Questions