I am using anonymous methods to handle events in a COM object. Once the program terminates, it appears that the resources I am using in the anonymous method are not being "closed correctly" in that I get a first chance exception (InvalidComObjectException) for every resource I was watching. I suppose this isn't a big deal, but it doesn't feel "right."
I can't fathom a way to access those captured variables outside the scope of the anonymous methods (which you're not supposed to be able to do, anyway). How can I close/dispose of the resources prior to exiting the application?
EDIT: After a brief re-read, it may not be clear what I'm doing here. I am writing a managed application that consumes a COM object.
Further Edit: I am using ArcGIS Engine to manipulate GIS data. In this particular case, I am using the VisibilityChanged event in ILayerEvents_Event to monitor when a GIS layer is made visible or invisible. The event ONLY passes a bool (visible or not visible) and NOT the layer name, so a method would need to be created for EACH layer to create it's visibility state change. Since I'm dealing with dynamic layers, I needed a way to somehow do this dynamically, hence the anonymous methods.
Inside the anonymoua method, I have an ILayer variable which grabs the ILayerEvents_Event from an outer loop (in an ILayer context) so that I know which layer I'm working with. It's at this point that I'm stuck. The functionality works and everything is grand until I exit the application, leaving those 20+ references hanging there with no place to go but to an exception.
I have no idea when the user will hide/show a layer for the last time, so there's no way to null things out on the last go. I suppose I can just leave it as is (or, perhaps there's a better way to do this than the anonymous methods) since it doesn't seem to be hurting anything. I just think I'm missing something.