captured-variable

How to avoid captured variables?

久未见 提交于 2021-02-07 13:17:25
问题 I'm having a problem with foreach(var category in categories) { foreach(var word in words) { var waitCallback = new WaitCallback(state => { DoSomething(word, category); }); ThreadPool.QueueUserWorkItem(waitCallback); } } When the DoSomething gets executed, it receives the latest value for each captured variable instead of the value I desired. I can imagine a solution for this, but it imagine you guys can come up with better solutions 回答1: The canonical way to solve this is to copy the values

Where is stored captured variable in Java?

…衆ロ難τιáo~ 提交于 2019-12-20 04:15:56
问题 I'm trying to understand concept of captured variable in Java. I found quite detailed article about it: http://www.devcodenote.com/2015/04/variable-capture-in-java.html and I'm not sure about bytecode part: Similarly, for accessing local variables of an enclosing method, a hidden copy of the variable is made and kept in the inner class file from where it accesses the variable. How can it be saved into class file (during compilation), when final primitive values may be not known in compile

Captured variable in a loop in C#

馋奶兔 提交于 2019-11-25 21:34:54
问题 I met an interesting issue about C#. I have code like below. List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add(() => variable * 2); ++ variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); } I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s. It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output. Is there a way to