我遇到了一个关于C#的有趣问题.我有如下代码.
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());
}
Run Code Online (Sandbox Code Playgroud)
我希望它输出0,2,4,6,8.但是,它实际输出5个10.
似乎是由于所有操作都涉及一个捕获的变量.结果,当它们被调用时,它们都具有相同的输出.
有没有办法解决这个限制,让每个动作实例都有自己的捕获变量?
我试图第一次嵌入多线程并遇到一些意想不到的问题,希望你能提供帮助.
这是给我带来麻烦的代码片段:
ArrayList recordsCollection = new ArrayList();
ArrayList batchCollection = null;
int idx = 0;
while(true)
{
// Some code to generate and assign new batchCollection here
recordsCollection.Add(batchCollection);
ThreadPool.QueueUserWorkItem(delegate
{
ProcessCollection(recordsCollection.GetRange(idx, 1));
});
Interlocked.Increment(ref idx);
}
private void ProcessCollection(ArrayList collection)
{
// Do some work on collection here
}
Run Code Online (Sandbox Code Playgroud)
一旦调用了Process Collection方法并且我试图遍历集合,我就会得到"底层列表中的范围无效".
提前致谢!
更新:伙计们,谢谢你们每一个人.通过应用您的建议,我能够大大简化并使其工作.