容器我用的是Dictionary<TKey,TValue>,有一个线程对这个容器进行写操作,另一个线程则对这个容器进行读操作
我用的Monitor来对这个容器进行加锁/读锁,
//这是需要传递的对象
class info
{
    int infono = -1;
    staticinfo  sf;
    public info()
    {
       sf = new staticinfo();
    }
}
class staticinfo
{
    string name = string.Empty;
}//写操作线程
class writeWork
{
   Dictionary<int,info> dic;
   public writeWork()
   {
      dic = new Dictionary<int,info>();
   }
   public Dictionary<int,info> m_Dic
   {      get{return dic;}
   }
   pulic void doWrite()
   {
       while()
       {
           info in = new info();
           Monitor.Enter(dic)
           try
           {
               //填充info内容
               dic.Add(in.infono,info);
            }finaly
            {
                Monitor.Exit(dic);
             }
           dic.Add(in.info,info);
       }   {
}//读取操作
class readWork
{
   writeWork write = new writeWork();
   public void read()
   {
      Monitor.Enter(write.m_Dic);
      try
      {
          foreach(info inf in write.m_Dic.values)
          {
                //读取操作
           }
       }finaly
      {
        Monitor.Exit(write.m_Dic);
      }
   }
}不知道我这样写对不对,这个思路运行是没有问题的,但是我总感觉似乎线程通讯有些问题,但又不知道该怎么解决,哪位高手能否给看一下.

解决方案 »

  1.   

    sample code as follows:private Mutex mWriter = new Mutex();
    private Mutex mReader = new Mutex();
    private int nReader = 0;//Writer operate
    mReader.WaitOne();//Get mutex to avoid other entering read block
    mWriter.WaitOne();//Get mutex to enter write block//Write operation heremWriter.ReleaseMutex();//Release mutex after leaving write block
    mReader.ReleaseMutex();//Release mutex to allow other enter read block
    //Reader operate
    mReader.WaitOne();//Get mutex to enter reader block
    nReader++;
    if( nReader == 1 )//First enters reader block
    mWriter.WaitOne();//Avoid to be write
    mReader.ReleaseMutex();// Allow other to enter//Read operation heremReader.WaitOne();//Get mutex to enter reader block
    nReader--;
    if( nReader == 0 )//The last leaves reader block
    mWriter.ReleaseMutex();//Release mutex to allow other enter write block
    mReader.ReleaseMutex();// Allow other to enter
      

  2.   

    to Knight94(愚翁) 
    首先感谢对我这个问题的回答.我问的问题就是一个对容器的操作
    也就是说对这个容器进行写入和读取的操作但是把容器放在什么地方,单独作为一个静态类来存放还是作为写入线程的成员变量,这会有什么区别,或者还有更好的办法? 运行的时候是否能保证数据的同步?
      

  3.   

    用Mutex该怎么对一个容器进行互斥操作呢?
    上面您说给出的是Mutex互斥函数调用 
    能否再给一段用Mutex对类或变量或代码段的操作的代码呢?
      

  4.   

    典型的生产者与消费者的问题,用lock(this)进行锁 ,用Sington保证资源访问的唯一性(网上和msdn都可以找到相关的用法)
      

  5.   

    to dyw31415926(dyw31415926)
    网上的确很多 我用Monitor try...finaly 其实和lock(this)是一样的道理啊
      

  6.   

    MSDN2005上有标准解答,不同于2003,2005的多线程有了更多的限制,它保持非创建线程无法修改到容器对象中的任何成员,如果要协调这种冲突,你需要学习MSDN为这个异常提供的几个标准示例,当然你可使用异步模式自己设计新的解决方案.
      

  7.   

    感谢 Knight94(愚翁) dyw31415926(dyw31415926)  ProjectDD()  朋友的解答