CLR Hosting lifetime issues bite again...

I’m looking into adding CLR deadlock detection into the CLR hosting code that’s used inside The Server Framework and, once again, the fact that you can’t cleanly shutdown the CLR host is causing me problems…

Since the CLR can’t be stopped by a host without terminating the host process (and that’s by design…) you need to be aware that any of the code that you have plugged into the CLR by way of the hosting interfaces can be called into during process shutdown. Since most of the code that you plug in will be in the form of COM objects you can rely on the COM reference counting to deal with cleaning up the objects (if the CLR could be relied on to release the references at any point…) but since you’re now writing code that out-lives main() you have to be intimately aware of how this code uses other code that might rely on module level static variables, and other nastiness. Sure you wouldn’t want to be relying on module level statics and the order of creation and destruction of those statics (which, as we know, is undefined across multiple modules) but if you’re using the version of STL that ships with VS2005 in any of your hosting COM objects then you are…

My implementation if IHostTaskManager uses a std::map to keep track of its tasks. During process shutdown the CLR calls into my task manager to put a task to sleep, to do this I need to locate the task in my map and doing that relies on iterating the STL map and that, if _HAS_ITERATOR_DEBUGGING is enabled, seems to manipulate a global lock… Unfortunately the global lock has been destroyed by the time the CLR decides to shutdown … Fortunately the global lock is kept alive by a reference counting class called _Init_locks which, although apparently undocumented, can be used to keep the locks that you need to use alive until the object that needs them is destroyed… So, by sticking an instance of _Init_locks into my task manager class I can make sure that it can iterate its collection after main() has returned and the process is shutting down…

But it would be much nicer and easier if the Stop() method on ICLRRuntimeHost wasn’t broken by design…