Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ani's answer is correct. Summarizing and adding some details:</p> <blockquote> <p>Since the delegate captures variable this._bar, does it implicitly hold to the instance of B? </p> </blockquote> <p>Yes. "this" is captured.</p> <blockquote> <p>Will the instance of B be referenced through event handler and captured variable by an instance of A?</p> </blockquote> <p>Yes.</p> <blockquote> <p>Would it be different if _bar were a local variable of the AttachToAEvent method?</p> </blockquote> <p>Yes. In that case the closure object would hold on to the local; the local would be realized as a field of the closure.</p> <blockquote> <p>Since in my case an instance of A lives far longer and is far smaller than an instance of B, I'm worried to cause "memory leak" by doing this.</p> </blockquote> <p>You are absolutely right to worry. Your situation is already bad, but in fact the situation can be <em>considerably worse</em> when you have <em>two</em> anonymous functions in play. Right now all anonymous functions in the same local variable declaration space share a common closure, which means that the lifetimes of <em>all</em> closed-over outer variables (including "this") are extended as far as the <em>longest lived</em> of all of them. See my article on the subject for details:</p> <p><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/06/06/fyi-c-and-vb-closures-are-per-scope.aspx" rel="noreferrer">http://blogs.msdn.com/b/ericlippert/archive/2007/06/06/fyi-c-and-vb-closures-are-per-scope.aspx</a></p> <p>We hope to fix this in a hypothetical future version of C#; we could be partitioning the closures better instead of creating one big closure. However that is not going to happen any time soon. </p> <p>Moreover, the "async/await" feature of C# 5 will also likely exacerbate situations in which locals end up living longer than you'd expect. None of us are thrilled with this, but as they say, the perfect is the enemy of the awesome. We have some ideas about how we can tweak the codegen of async blocks to improve the situation, but no promises.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload