rubiktubik
rubiktubik

Reputation: 1001

C#: Multiple Event Raises

My question is related to events:

I have Class with a TaskAComplete Event that is raised when TaskA is complete.

When a button is pressed I subscribe the TaskACompleteEvent

MyObject.TaskAComplete += new EventHandler(MethodToCall);

But in other Event I want to Unsubscribe from the TaskAComplete Event when the Event occurs the first time.

with:

MyObject.TaskAComplete -= MethodToCall;

And then when the Button is pressed the next time to Subscribe the TaskAComplete Event again.

Now when i start the Application and click on the Button the first time it raises the Event correctly.But when i click on the Button the second time the Event is raises two times in a row. (Third time click ->Event is raised three times in a row and so on..)

When i Subscribe the Event in the Contructor of the Form it only raises one time at every click.

Why the Event comes several times?

Upvotes: 1

Views: 2068

Answers (2)

David Pfeffer
David Pfeffer

Reputation: 39872

When you subscribe to an event, you are subscribing by providing a delegate to a method. A delegate is effectively a strongly-typed, object-oriented approach to a C/C++ function pointer.

This delegate then goes into the list of calls for the event.

When you do new EventHandler(MethodToCall) you are explicitly creating that delegate. However, when you do -= MethodToCall, you are removing an "automatic" delegate. It is as if you wrote -= new EventHandler(MethodToCall). Obviously, this new delegate is not the one in the invocation list.

To do what you want, on add, you need to save the new delegate in a variable, which you can later remove. For example:

var handler = new EventHandler(MethodToCall);
MyObject.TaskAComplete += handler;
// later on
MyObject.TaskAComplete -= handler;

Upvotes: 1

Jon
Jon

Reputation: 437754

You only need to subscribe to the event once. If you subscribe multiple times with the same handler, that handler will be invoked multiple times just like you are seeing.

Why do you want to unsubscribe from the TaskAComplete event in the first place? If your other code is correct, you will get it exactly once for each task.

Upvotes: 0

Related Questions