How to know if Revit API is in Context.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
After messing with Revit API for so long I figured out a reliable way to know if your code is in Revit API Context or not.
By default, Revit API throws exceptions if your code is trying to execute Revit API methods in a WPF modeless view for example, that's the reason you need to use ExternalEvent to execute Revit API code in context.
Sometimes it is needed to know if the code is running in context or if not, to just execute the Revit API code right away or send it to ExternalEvent to be executed.
If you have access to UIApplication or UIControllerApplication, and if you try to subscribe to an event outside Revit API context you are gonna have this exception: Invalid call to Revit API! Revit is currently not within an API context.
Meaning you could use that to know if your code is in context or not.
Here is a code sample and video: https://ricaun.com/revit-api-context/
I'm this technique using my open-source library to manage the creation of ExternalEvent if it is not in context and enable it to run Revit API asynchronously. https://github.com/ricaun-io/ricaun.Revit.UI.Tasks
I'm planning to create a full tutorial in the future about this library on my YouTube channel.