How to prevent RuntimeMethodInfo objects from leaking memory?

95 views Asked by At

I’m comparing two snapshots taken using dotMemory profiler, and I find that there are a number of RuntimeMethodInfo objects that survived through two snapshots. These objects represent methods of a type using reflection, and they take up a lot of memory. I want to know what they are and how to get rid of them. The memory held can be gigantic in the real application. I don’t want them to retain too much memory and cause performance problems.

Here is a screenshot of the snapshots' comparison, showing the RuntimeMethodInfo objects in the sample code and in the real application. enter image description here

And here is a sample code snippet to produce the snapshots:

class Program
{
    static void Main()
    {
        var eventSource = new MyEventSource();

        WeakEventManager<MyEventSource, EventArgs>.AddHandler(eventSource, "MyEvent", EventHandlerMethod);
        MemoryProfiler.GetSnapshot();

        eventSource.RaiseEvent();
        WeakEventManager<MyEventSource, EventArgs>.RemoveHandler(eventSource, "MyEvent", EventHandlerMethod);

        MemoryProfiler.GetSnapshot();

    }

    private static void EventHandlerMethod(object sender, EventArgs e)
    {
    }
}

public class MyEventSource
{
    public event EventHandler<EventArgs> MyEvent;

    public void RaiseEvent()
    {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}
0

There are 0 answers