c# - When are method variables, accessible in an anonymous method, garbage collected? -


for instance is necessary add timer instance list doing here prevent timer being garbage collected? tyically if callback not anonymous aswer yes, since anonymous imagine variables in method block accessible in anonymous method block garbage collected when anonymous method completes? in case no need save ref doing..:

private static list<timer> timers = new list<timer>();  public static void runcallbackafter(action callback, int secondstowait) {         timer t = null;         t = new timer(new timercallback(delegate(object state)             {                 somethread.begininvoke(callback);                 timers.remove(t);             }), null, secondstowait*1000, timeout.infinite);         timers.add(t); } 

the objects referred captured variables in anonymous method not eligible garbage collection until delegate created anonymous method eligible garbage collection.

however, if it's timer has reference delegate, , nothing else has reference timer, suspect both eligible garbage collection, assuming indeed kind of timer need keep reference to. (i seem remember timers do require , don't. can't remember which.)

also, if removed timers.remove(t) call within anonymous method wouldn't capturing t in first place. it's captured variables have prolonged lifetimes... not every variable in method contains anonymous method.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -