C# 从其他线程向列表中添加项目
我的课程是:C# 从其他线程向列表中添加项目,c#,multithreading,C#,Multithreading,我的课程是: class SomeClass{ class Connection{//some fields} static List<Connection> connections { get; set; } public SomeClass( \\params etc) { connections = new List<Connections>(); // initialize connections lis
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;
}
}
class-SomeClass{
类连接{//某些字段}
静态列表连接{get;set;}
公共类(\\params等)
{
连接=新建列表();//初始化连接列表
//初始化其他一些私有变量
// ...
mainClassThreadMethod();
}
私有void mainClassThreadMethod()
{
while(true)
{
螺纹t;
连接p=新连接({\\instantiate the class})
//这个代码在p初始化之前不会执行……换句话说,这个循环不会快速执行几次。
t=新线程(新的参数化线程启动(startThread));
t、 启动(p);
}
}
私有void startThread(对象o)
{
//向列表中添加新连接
连接。添加((连接)o));
}
公共列表getConnections()
{
返回连接;
}
}
为什么在向列表添加新连接后,如果调用getConnections方法,它会返回一个空列表?我想这是因为我添加了来自不同线程的项目。我怎样才能知道这件事 上面的代码中有几个问题,但坚持问题,要同步列表(允许从不同线程添加),您可以(1)实现自己的锁定,或(2)使用。 我会选择2,但对你来说:
- 不,这可能不是由于添加了来自不同线程的任何内容造成的
- 为什么要从
内部添加?在实例化线程之前,您拥有connection对象,因此您可以轻松地从同一线程调用startThread
,从而无需任何锁定connections.Add(connection)
- 为什么在线程加速过程中会有一个while(true)循环