Memory Leak and Weak References

2019-05-13 16:31发布

问题:

I'm having an issue which looks like a memory leak in one of my applications (the application uses more memory over time, an after about a week of work it hangs).

I've detected and fixed some leaks related to classes I've written (comparing heap dumps taken with sos.dll revealed them quickly), and those no longer increase in number.

Currently, the only thing that dramatically increases over time are WeakReference instances, which increase at a steady rate of 1,000 new WeakReference instances per minute.

My code doesn't use WeakReference directly, I never create those myself.

What could cause so many WeakReference instances to be created?

I'm using VB.NET, Visual Studio 2008 and .NET 3.5

回答1:

Yes, this is a fairly infamous leak in VB.NET assemblies. It is caused by weak references that keep track of events that are declared with the WithEvents keyword. This tracking is done to support Edit and Continue. It leaks one instance of WeakReference for every one WithEvents event declared in a class. The debugger needs to be attached to release those WeakReference objects.

The workaround is simple. Ship the Release build, not the Debug build.