我有一个班级:
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;
}
}
为什么在向列表添加新连接后,如果我再调用getConnections方法,它会返回一个空列表?我认为这是因为我从不同的线程添加项目。我怎样才能跟踪这个?
答案 0 :(得分:2)
上面的代码中有几个问题,但是坚持要求的问题,要同步列表(允许从不同的线程添加),你可以(1)实现自己的锁定,或者(2)使用{{ 3}} 强>
我会去#2,但在你的情况下:
startThread
内添加?在实例化线程之前,您有连接对象,因此您可以从同一个线程轻松调用connections.Add(connection)
,从而无需任何锁定。