add items to a list from a different thread
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 开发者_StackOverflow中文版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?
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:
- No, it's probably not caused by adding anything from a different thread
- Why would you even want to add from inside
startThread
? You have the connection object before you instantiate a thread, so you can easily callconnections.Add(connection)
from the same thread thereby eliminating the need for any locking. - Why is there a while(true) loop around the thread spin-up process?
精彩评论