Persistent engine and manual cleanup

What would be the proper way to clean up all my stuff after execution if I have to use persistent engine because of a modeless window? I’m also experimenting with DirectContext3D so i really don’t wanna leave a mess. I guess I have to subscribe to the form’s Closed event but what’s next? script.exit() could be enough?
@eirannejad what is your suggestion?

What sort of stuff do you wanna clean up? The pyRevit IronPython engine normally runs the script below to clean the scope from public instances:

for __deref in dir():
    if not __deref.startswith('__'):
        del globals()[__deref]

And how often is it run? I mean how long the globals from a script with persistent engine “survive”? because I’ve found if I run my script this way over time it gets a bit slower and slower. Ideally, on every run all of the globals are overwritten by new data, but I would like to narrow this issue down.
Also, what method would you suggest to don’t let users re-run the script with the modeless window untill a previous instance is still open? Store the open state of the window in a data file?

Edit: okay, I’ve checked IronPythonEngine.cs, and the cleanup you mentioned is only called if (!ExecEngineConfigs.persistent) which is the exact opposite of what I was asking about. So the question is still valid, what happens to the globals of a script run on persistent engine? What’s the worst that could happen?

Can I call that cleanup function in the closed event of my wpf window?

Ok, I’ve tried, but caliing globals() throws the following exception: SystemError: Object reference not set to an instance of an object. , but not only in the closed event, in the main script as well.