简体   繁体   中英

.NET Event Handling When an Event Is Fired While Another Event Handler is Already Running

There is an issue that makes me curious about for quite some time.
Assume this scenario:
You created a program in C#, which has some classes inwhich you defined some events,
and other classes consume those events - they implement event handler methods for them.

My question: What are the CLR's "rules" for running the event handler(s), for cases where events happen simultaneously?

If one event handler is running, and another event was raised now, will the CLR let the current event handler finish, and then just go to the next event handler? (the "second" event might be a second raise of the same event, or a different event)
Or is there a case where the CLR pauses the current event handler due to an event that came in the middle, then runs the second event handler, and then resumes back to the middle of the first event handler that was left?

Any info or article that makes an order in this, will be greatly appreciated.

BTW:
For this question, please assume 2 possible situations:
1) The classes with the events and event handlers are not Controls
(simple classes that you write, that inherit type object and not type Control)
2) The classes with the events and event handlers are inheriting class Control (Windows Forms)

I mention this because maybe the behavior/rules are different between the two.

Also, I would be grateful if you can relate to following things, that might affect the answers to these 2 questions:
- Application.DoEvents() method
- Timer s
- any other class/method like this that might give different results beyond the simple ones that we might think of in the "normal" case..

Thank you

This has nothing to do with the CLR or the language. It's purely based on the specific implementation of the class defining the method. It can be written such that it fires of the event while handlers for a previous invocation are still running, or it could not. If you're dealing with a winforms program then most object firing events are firing them in the UI thread, so since there is only one thread that can be firing the events it can't ever fire them while other handlers are still running, but there are other objects that aren't forcing their usage to a single thread and as such can fire an event while handlers for a previous invocation are still running.

So all you can really do is look at the documentation/source code or do some experimental tests to see what any particular class does, or be safe and assume the worst case. There is no general case answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM