C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Accidental capture of expensive resources

Chapter 5: Fast-tracked delegates: 5.5.7

Created: 2/24/2008
Last updated: 2/24/2008

There's a note of caution I originally wanted to include in the chapter, but it ended up making the whole thing too long - and frankly too negative. In the current implementation of captured variables, any variable which is captured by any anonymous method is captured by all anonymous methods which capture a variable from the same scope. This can - in very rare scenarios - mean that something isn't eligible for garbage collection for far longer than anticipated.

Rather than go over the details, I'll redirect you to Eric's blog post on the topic. Note that this behaviour certainly isn't mandated, so it's possible that it may be fixed in a future version of the compiler - but it's unlikely to affect very many people.