Can using lambdas as event handlers cause a memory leak?

前端 未结 5 873
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 21:43

Say we have the following method:

private MyObject foo = new MyObject();

// and later in the class

public void PotentialMemoryLeaker(){
  int firedCount =          


        
5条回答
  •  北海茫月
    2020-12-08 22:02

    Your example just compiles to a compiler-named private inner class (with field firedCount and a compiler-named method). Each call to PotentialMemoryLeaker creates a new instance of the closure class to which where foo keeps a reference by way of a delegate to the single method.

    If you don't reference the whole object that owns PotentialMemoryLeaker, then that will all be garbage collected. Otherwise, you can either set foo to null or empty foo's event handler list by writing this:

    foreach (var handler in AnEvent.GetInvocationList()) AnEvent -= handler;
    

    Of course, you'd need access to the MyObject class's private members.

提交回复
热议问题