Reputation: 3173
I'm trying to fix on an old, clunky, complicated legacy system with a memory leak. I've traced the problem back and the best way to describe the memory leak is that it's "by design." In simple terms, there is an event observer that is holding a reference to objects after they've been abandoned. For this reason objects can't be collected by the garbage collector and stay in memory indefinitely.
Is there a way to get a collection of objects that currently hold a reference to an instance?
Upvotes: 2
Views: 413
Reputation: 2596
Use WinDBG. Here is example of finding memory leaks using WinDBG in Tess blog.
Upvotes: 1
Reputation: 29186
You could try getting technical by using WinDbg with the Sosex extension DLL. If you're not familiar with WinDbg then try reading Tess Ferrandez's blog which is a goldmine of .NET debugging information.
Basically, Sosex.dll has a !Refs
command which lists objects that have a reference to a specific object address you give. For example:
Usage:
!refs <hexObjectAddr>
Lists all references held by the specified object
Lists all references to the specified object (searches heaps, stacks, registers, handle tables and the freachable queue)
Refs are listed in the following format:
hexAddr decSize strTypeName
Sample output:
0:000> !sosex.refs 7fff2970
Objects referenced by 7fff2970:
7fff1100 64 System.IO.__ConsoleStream
7fff1388 136 System.Text.SBCSCodePageEncoding
7fff2c50 48 System.Text.DecoderNLS
7fff2c80 280 System.Byte[]
7fff2d98 536 System.Char[]
7fff1140 24 System.Byte[]
Objects referencing 7fff2970:
7fff2fb0 32 System.IO.TextReader+SyncTextReader
``
Please note that this is a very hardcore solution, which will require a fair bit of preparation if you;re new to this. However, it can be a very powerful way to debug .NET apps.
Upvotes: 1
Reputation: 1500675
No, not unless you're using the debugger API.
One option for this sort of thing is the WeakReference
class. If you search for WeakReference
along with events, you'll find quite a lot of documents with suggestions for how to cope with exactly this issue. None of them are particularly clean, from what I remember, but they should work reasonably well.
As an example, this page discusses a number of different approaches.
Upvotes: 3