0

We have an application that is well beyond a quick design improvement and is in a state where everything works, but there is a memory leak. We cannot use any of the popular profilers out there because we're sandboxed inside the Unity3D engine in some old version of Mono.

We have many transient objects with many events at play, and we suspect some poor design and missing event unsubscriptions could be at play here.

I'd love to know if anyone can think of some simple ways to scan the project for missing event unsubscribes. I'm hoping it is possible to use Visual Studio itself to write a script that can look at an event and tell us if the -= and += are in equal existence in the project.

4
  • you can search the solution using regex
    – Xi Sigma
    Apr 7, 2015 at 19:13
  • @decoherence that won't take in to account conditional subscription/un-subscription.
    – Moo-Juice
    Apr 7, 2015 at 19:16
  • A solution that can deal with conditional sub/unsub would be amazing, but I'd also accept something that can simply tell me if the -= are in equal amounts. @decoherence how would one regex test all events in a solution for equal sub/unsub?
    – S.Richmond
    Apr 7, 2015 at 20:42
  • 1
    @S.Richmond i would write a small console app that goes though all *.cs files in the directory and it involves 2 regular expressions one to match suscriptions which is ([A-Za-z]*.*)\s*(\+\=)\s*([A-Za-z]*.*) and ([A-Za-z]*.*)\s*(\-\=)\s*([A-Za-z]*.*) to match the unsub, put the matches of each in a list and compare and make sure you call s.Replace(" ","") to ignore spaces before adding the first group of a match to the list, note that i haven't tested the regular expressions and i am not a regex expert, but its too simple it should work fine, again revise the regexes i provided.
    – Xi Sigma
    Apr 7, 2015 at 20:59

1 Answer 1

0

Counting -= and += in code is very error-prone, because event-related memory leaks are most often caused by some conditional execution.

If you're short of profilers, you could use Reflection to enumerate any object's field-like event subscribers at any given time using something like this:

public static class InvocationHelper
{
    public static Dictionary<string,Delegate[]> GetInvocationList<TClass>(TClass source)
    {
        if (null == source)
            return new Dictionary<string, Delegate[]>();

        var retval = new Dictionary<string,Delegate[]>();

        var members = typeof (TClass).GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).
            Where(t=>t.MemberType == MemberTypes.Event).ToArray();

        foreach (var memberInfo in members)
        {
            var field = typeof (TClass).GetField(memberInfo.Name,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            if (field == null) 
                continue;

            var delegateField = field.GetValue(source) as Delegate;

            if(null == delegateField)
                continue;

            retval[memberInfo.Name] = delegateField.GetInvocationList();                
        }

        return retval;
    }
}

Method above walks through all events in source and returns dictionary with invocation lists for events encountered.

This works only for field-like events (and for custom events you can count subscribers manually).

For example, suppose you have some class with field-like event SomeEvent:

public class SomeEventHolder
{
    public delegate void SomeEventHandler(bool par);

    public event SomeEventHandler SomeEvent;

    protected virtual void OnSomeEvent(bool par)
    {
        var handler = SomeEvent;
        if (handler != null) handler(par);
    }
}

You create instance of this class and subscribe three times to SomeEvent but unsubscribe only once:

var instance = new SomeEventHolder();

//....

instance.SomeEvent += inst_SomeEvent;
instance.SomeEvent += inst_SomeOther;
instance.SomeEvent += inst_SomeEvent;
instance.SomeEvent -= inst_SomeEvent;

Then, you can call GetInvocationList for instance and get subscribers left, and, say, output their list to console:

var invocationList = InvocationHelper.GetInvocationList(instance);

foreach (var item in invocationList)
{
    Console.WriteLine("Subscribers for {0} : {1}",
        item.Key,
        string.Join(Environment.NewLine, item.Value.Select(s => s.Method.ToString())));
}

This would result in

Subscribers for SomeEvent : Void inst_SomeEvent(Boolean)
Void inst_SomeOther(Boolean)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.