Reputation: 36070
I have a class as:
class SomeClass{
class Connection{//some fields}
static List<Connection> connections { get; set; }
public SomeClass( \\params etc)
{
connections = new List<Connections>(); // initialize connections list
//initialize some other private vars
// ...
mainClassThreadMethod();
}
private void mainClassThreadMethod()
{
while (true)
{
Thread t;
Connection p = new Connection ( { \\instantiate the class})
// this code will not execute until p is initialized... In other words this loop will not execute several times quickly.
t = new Thread(new ParameterizedThreadStart(startThread));
t.Start(p);
}
}
private void startThread(object o)
{
//add a new connection to the list
connections.Add((Connection)o));
}
public List<Connection> getConnections()
{
return connections;
}
}
why is it that after adding new connections to the list if I then call the getConnections method it returns a null list? I figure it is because I am adding the items from a different thread. How can I keep track of this?
Upvotes: 0
Views: 1560
Reputation: 2335
You have several problems in the code above, but sticking to the question asked, to synchronize the list (allow adding from different threads) you can (1) implement your own locking, or (2) use http://msdn.microsoft.com/en-us/library/3azh197k.aspx.
I'd go for #2, but in your case:
startThread
? You have the connection object before you instantiate a thread, so you can easily call connections.Add(connection)
from the same thread thereby eliminating the need for any locking.Upvotes: 2