I'm trying to learn about threads for an assignment for school, and I'm trying to get two threads to empty a collection. The code I came up with so far throws an exception, saying that the collection got modified.
First I had a while loop in the locked code part, but then (of course ;-)) only one thread empties the collection.
My question is, how can I have a loop in which the threads both take turns in emptying the collection?
class Program
{
private static List<int> containers = new List<int>();
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
containers.Add(i);
}
Thread t1 = new Thread(() => { foreach (int container in containers) { GeefContainer(); } });
t1.Name = "Kraan 1";
t1.Start();
Thread t2 = new Thread(() => { foreach (int container in containers) { GeefContainer(); } });
t2.Name = "Kraan 2";
t2.Start();
Console.Write("Press any key to continue...");
Console.Read();
}
static void GeefContainer()
{
lock (containers)
{
int containerNummer = containers.Count - 1;
//Container container = containers[containerNummer];
//Console.Write("Container {0} opgehaald... Overladen", containerNummer);
Console.WriteLine("Schip: Container {0} gegeven aan {1}", containerNummer, Thread.CurrentThread.Name);
//Gevaarlijk, want methode aanroepen kan klappen
containers.RemoveAt(containerNummer);
}
}
}