Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Silverlight leak memory when using COM?

We discovered this issue when hosting a legacy COM component in our Out Of Browser Silverlight application, first thinking it was an issue with our COM component.

Narrowing it down to hosting the most basic COM component imaginable still had the memory leak, however. This COM component used for testing is written in .NET, and simply sends events back to the Silverlight application every time a timer fires. Each event contains a single string only.

When running the Silverlight application, the process memory usage keeps growing. Profilers show no increase in managed memory, indicating that there's a leak in the Silverlight runtime / COM implementation.

Has anyone else seen this issue, and if so, have you been able to work around it?

Edit: Repro project now available at http://bitbucket.org/freed/silverlight-com-leak

like image 913
SoftMemes Avatar asked Nov 19 '10 15:11

SoftMemes


People also ask

Can a website cause a memory leak?

Most web apps can leak memory and no one will ever notice. Not the user, not the website author – nobody. There are a few reasons for this. First off, browsers are well aware that the web is a leaky mess and are already ruthless about killing background tabs that consume too much memory.

What causes memory leak in Web application?

A memory leak is simply caused by reference chaining which is held up in the PermGen and cannot be garbage-collected.

Why is my memory leaking?

A memory leak occurs when a process allocates memory from the paged or nonpaged pools, but does not free the memory. As a result, these limited pools of memory are depleted over time, causing Windows to slow down.


1 Answers

Looking at your code, the string you pass back & forth is (11 characters + terminating zero) = 24 bytes in unicode. In COM Automation, BSTR are used wich adds 4 bytes for the leading pointer (32-bit), and you multiply that by 10000, wich is 10000 * 28 = 280000 bytes.

It means every millisecond (the timer's value is 1) you will allocate a lot of memory, and in .NET a 280000 bytes chunk will probably be allocated in the large object heap (> 85000 bytes). The result of hitting hard on the LOH is most of the time... problems with memory, as seen here for example: Large Object Heap Fragmentation

This is maybe something you should check. One simple thing to test is to reduce the size of your BigMessage. You can also dive in deep with WinDBG: http://blogs.msdn.com/b/tess/archive/2008/08/21/debugging-silverlight-applications-with-windbg-and-sos-dll.aspx and check what's really going on under covers.

like image 92
Simon Mourier Avatar answered Oct 26 '22 23:10

Simon Mourier