views:

72

answers:

4

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?

+3  A: 

I do not know such way.
But - Collection of Weak References might be handy in such situations.
Take a look here

Itay
+1  A: 

Use WinDBG. Here is example of finding memory leaks using WinDBG in Tess blog.

Yauheni Sivukha
+3  A: 

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.

Jon Skeet
+1  A: 

Hi there.

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.

Cheers. Jas.

Jason Evans