Jeff B
Jeff B

Reputation: 8972

How can I determine if a delegate is an anonymous lambda?

We have a library that imitates events and provides some enhanced functionality. It does this mainly by keeping track of delegates you register with it. Like events it has the potential for memory leaks.

I'm changing the class that managers the delegates over to using weak references but I'm running into a problem: if you register an anonymous lambda and GC.Collect the delegate gets collected. I'd like to programmatically determine if a delegate being registered is an anonymous lambda and use a strong reference instead for that case.

Q: How can I determine if a delegate is an anonymous lambda (or more generally, something that semantically we wouldn't expect to have it 'disappear' right away).

One way that might work is checking if the Delegate.Target property is null, but this catches static methods in general, so that might not be what I want. The other option is check if IsSpecialName and IsStatic are set to true on the Delegate.Method property. Not sure if that's the right thing to do either.

One concern is that if I have strong references to lambdas using members of the class it was registered in, we'll still end up with the same memory-leak scenario... or we might access a disposed object. Is there a graceful way to handle this?

Upvotes: 2

Views: 340

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

Basically, you can't. At run-time anonymous lambda's are methods. You could check the method name:

static int Foo() { return 0; }

void Main()
{
    Func<int> foo = Foo;
    Func<int> bar = () => 0;
    Console.WriteLine(foo.Method.Name); // Foo
    Console.WriteLine(bar.Method.Name); // <Main>b__0
}

That's a pretty bad approach, but it may be the only way since foo and bar are otherwise indistinguishable.

Upvotes: 1

Related Questions