ringos staro
ringos staro

Reputation: 27

run action after an event is completed in .NET/C#

Action1 triggers Event1 Event2 in this order.

Action2 also triggers Event2.

I need to execute a method after Event1 is triggered AND COMPLETED.

How would I achieve this in C#/.NET?

The key is that I need to execute that method when the event is completed, because only then I have access to certain properties of an object.

I was thinking of adding a variable globally at class level and assign it a value inside Event1 handler. Then checking inside Event2 handler if the variable was initialised, which means we are at a stage where Event1 was completed. And then inside Event2 handler adding my method.

This doesn't seem to work because Event2 is triggerred extremely often when Action2 is executed (an action I don't care about) and I get a stack overflow error message. Is there a good way to actually make this work?

Can(how) I do something like override the library and add a new event (that does nothing) triggered when an existing event is completed; then I would use the new event just to attach a handler to it and put my method there.

These events and actions are inherent to a framework so I don't have much control over them as their definition is hidden inside .net libraries. So I'm interested in some general principles and tricks and these are the limitations/setbacks.

Some sample code can be found here: https://stackoverflow.com/questions/41969955/how-to-use-invoke-to-call-a-method-after-an-event-was-finished

Upvotes: 1

Views: 4557

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61349

Event handling is by its nature synchronous (assuming somebody doesn't use async void or start their own thread in a handler) so the following code:

Event1?.Invoke();
//Do stuff after Event1

Will already do what you are asking. If you need to wait for some asynchronous task that is kicked off by a handler of Event1 then you will need to do that apart from the event invocation process.

Upvotes: 3

Related Questions