Private field captured in anonymous delegate

前端 未结 3 2075
傲寒
傲寒 2021-02-07 21:49
class A
{
   public event EventHandler AEvent;
}
class B
{
   private A _foo;
   private int _bar;

   public void AttachToAEvent()
   {
      _foo.AEvent += delegate()
         


        
3条回答
  •  粉色の甜心
    2021-02-07 22:06

    Ani's answer is correct. Summarizing and adding some details:

    Since the delegate captures variable this._bar, does it implicitly hold to the instance of B?

    Yes. "this" is captured.

    Will the instance of B be referenced through event handler and captured variable by an instance of A?

    Yes.

    Would it be different if _bar were a local variable of the AttachToAEvent method?

    Yes. In that case the closure object would hold on to the local; the local would be realized as a field of the closure.

    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.

    You are absolutely right to worry. Your situation is already bad, but in fact the situation can be considerably worse when you have two 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 all closed-over outer variables (including "this") are extended as far as the longest lived of all of them. See my article on the subject for details:

    http://blogs.msdn.com/b/ericlippert/archive/2007/06/06/fyi-c-and-vb-closures-are-per-scope.aspx

    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.

    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.

提交回复
热议问题