Find out what called Finalize?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi everyone,

I have a long-running application (sits in the system tray waiting for
something to do and interacts with the user via form and some hardware)
containing an object (a reference to the aforementioned hardware and its
associated functionality) that occasionally will become 'nothing' i.e. when I
attempt to access it after a period of time, I get a null reference exception.

I couldn't find a path in my code that releases the object unintentionally,
so I was wondering if there was a way to tell if the garbage collector
released it or what. This object implements IDisposable because it contains
some unmanaged resources- it wraps a device driver- but I haven't had any
luck in finding out what chunk of code called Dispose.

Any suggestions that would help me troubleshoot this problem? I'd really
appreciate it.
 
Mike,
This object implements IDisposable because it contains
some unmanaged resources- it wraps a device driver- but I haven't had any
luck in finding out what chunk of code called Dispose.

Can't you simply put a breakpoint in Dispose?


Mattias
 
Actually, it's not something that I've been able to reproduce while
debugging, as it is difficult to simulate the operating environment. When
the application is under heavy use by our people it occurs more frequently.

I can set up a log to write data to a file in the dispose method, but I'm
not sure what the most useful data to record would be. Also, are there
situations in which the dispose method might not get called? It's a fairly
new area for me, as I've pretty much always worked with managed code and
haven't had to worry about Dispose.

Mike
 
You could add some diagnostic test code to capture the creator's callsite
(use the StackWalk to find it), and then write that out if the object gets
finalized or disposed. Or you could save the entire stack trace when the
object is created.

If you implement both Dispose and a finalizer you will get notified when it
either is explicitly destroyed (Dispose) or if it is no longer reachable
(the creator abandoned it) when the Finalizer is called.

So long as the object is reachable the GC will not collect it; it wont just
go away on its own.
 
Back
Top