Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your code has a few problems (some you and others have identified):</p> <ul> <li>The anonymous delegate cannot be removed from the event as coded.</li> <li>The anonymous delegate will live longer than the life of the method calling it because you've added it to <strong>FoundStep</strong> which is a member of <strong>this</strong>.</li> <li>Every entry into <strong>FindStepsByType</strong> adds another anonymous delegate to <strong>FoundStep</strong>.</li> <li>The anonymous delegate is a closure and effectively extends the lifetime of <strong>retval</strong>, so even if you stop referencing <strong>retval</strong> elsewhere in your code, it's still held by the anonymous delegate.</li> </ul> <p>To fix this, and still use an anonymous delegate, assign it to a local variable, and then remove the handler inside a <strong>finally</strong> block (necessary in case the handler throws an exception):</p> <pre><code> public List&lt;IWFResourceInstance&gt; FindStepsByType(IWFResource res) { List&lt;IWFResourceInstance&gt; retval = new List&lt;IWFResourceInstance&gt;(); EventHandler&lt;WalkerStepEventArgs&gt; handler = (sender, e) =&gt; { if (e.Step.ResourceType == res) retval.Add(e.Step); }; this.FoundStep += handler; try { this.Start(); } finally { this.FoundStep -= handler; } return retval; } </code></pre> <p>With C# 7.0+ you can replace the anonymous delegate with a local function, achieving the same effect:</p> <pre><code> public List&lt;IWFResourceInstance&gt; FindStepsByType(IWFResource res) { var retval = new List&lt;IWFResourceInstance&gt;(); void Handler(object sender, WalkerStepEventArgs e) { if (e.Step.ResourceType == res) retval.Add(e.Step); } FoundStep += Handler; try { this.Start(); } finally { FoundStep -= Handler; } return retval; } </code></pre>
 

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