ViewActivated Event fires multiple times when toggling between open views
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
In my program, I have several methods that need to execute each time the user activates a different view. These methods are triggered using the ViewActivated event. I've been seeing some unexpected behavior which led me to break it down and do some testing with some very simplified conditions.
Based on my testing, I've concluded that under certain conditions the ViewActivated event appears to fire (3) consecutive times when the user has only toggled from one open view to another open view. I verified this using a simple MessageBox.Show() which outputs the name of the newly activated view and the previously active view. As you will see in my attached reproducible test case, I have already verified that I subscribe to the event only once. If there was a redundant subscription to the event, I would expect the problem to manifest during all view activations, but I have only observed the behavior when toggling between already open views. Opening a new view does not result in multiple fires of the event. This behavior is evident in Revit 2019, Revit 2020, and in Revit 2021.
Here is an example of how the problem would manifest. Say that you have two open plan views ("Level 1" and "Level 2"), where "Level 1" is currently active. If you then activate the "Level 2" plan by clicking it's tab, then you will see three consecutive messages:
1.) First, the requested view is activated:
2.) Then the original view is re-activated:
3.) Finally, the requested view is activated again:
To demonstrate this behavior, I've created a basic test case where all of the required code is included in a macro inside the attached Revit 2020 file. In order to observe the issue I've described here, simply open the Revit file, enable macros, and then run the RegisterEventHandler() method. Opening several views and then toggling between them several times will eventually result in the multiple firing I'm describing. See the link below for a short screen capture video clip of the multiple firing in action. You will note that the behavior does not occur immediately. It typically occurs after cycling through several open views:
https://www.screencast.com/t/9K7GjtMA886
I'm interested to hear if there is a problem with my implementation, or if there is a way to prevent this redundant firing of the event. The repetitive firing becomes particularly problematic for any time-consuming logic inside the event, because the user begins to experience multiple unnecessary delays.