[英]How to remove a list item from a lambda expression in c#?
If I have this 如果我有这个
private static List<Action> actions = new List<Action>();
private static void Main()
{
for (var i = 0; i < 10; i += 1)
{
Action action = async () => {
// want to remove this specific lambda item from the "actions" variable.
// is there something like this:
/*
Action this_action = this;
actions.Remove(this_action);
*/
};
actions.Add(action);
}
Parallel.Invoke(actions.ToArray());
Console.Write("\nPress any key to exit...");
Console.ReadKey();
}
How can I properly remove it from the list. 如何从列表中正确删除它。 I would need some kind of self reference?
我需要某种自我参考吗?
Note: 注意:
It's the action that was just run should be the one to be removed. 刚执行的操作应该被删除。 The actions may not finish in the same order as how they are added to the list, but the one that ran should be the one removed.
这些动作的完成顺序可能与将其添加到列表的顺序不同,但是执行的动作应该是删除的动作。 And I don't want to remove them all at the same time, only as they finish.
而且我不想同时删除它们,只能等它们完成后再删除。
Thanks 谢谢
You can just use the reference to action
to remove the action's instance. 您可以仅使用对
action
的引用来删除操作的实例。 Closure will make sure that the reference is pointing to the correct object. 关闭将确保引用指向正确的对象。
for (var i = 0; i < 10; i += 1)
{
Action action = null;
action = () => {
actions.Remove(action);
};
actions.Add(action);
}
Parallel.Invoke(actions.ToArray());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.