Reputation: 43843
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
Upvotes: 0
Views: 175
Reputation: 24671
You can just use the reference to action
to remove the action's instance. 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());
See Fiddle for a working example.
Upvotes: 2