从不同的线程将项添加到列表中

时间:2011-08-29 22:07:43

标签: c# multithreading

我有一个班级:

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方法,它会返回一个空列表?我认为这是因为我从不同的线程添加项目。我怎样才能跟踪这个?

1 个答案:

答案 0 :(得分:2)

上面的代码中有几个问题,但是坚持要求的问题,要同步列表(允许从不同的线程添加),你可以(1)实现自己的锁定,或者(2)使用{{ 3}}

我会去#2,但在你的情况下:

  • 不,这可能不是由其他线程添加任何内容造成的
  • 为什么你甚至想从startThread内添加?在实例化线程之前,您有连接对象,因此您可以从同一个线程轻松调用connections.Add(connection),从而无需任何锁定。
  • 为什么在线程旋转过程中有一个while(true)循环?