0

我正在为 wp7 开发一个应用程序。我需要同步读写。所以我创建了这个类

public class SynchronizedPacketQueue
{
    [DataMember]
    public List<Packet> packetsQ;

    public SynchronizedPacketQueue()
    {
        packetsQ = new List<Packet>();
    }

    public int Count
    {
        get { return packetsQ.Count; }
        private set{}
    }


    public Packet Dequeue()
    {
        lock (packetsQ)
        {
            if (packetsQ.Count == 0)
            {
                Monitor.Wait(packetsQ);

            }
            Packet packet = packetsQ[0];
            packetsQ.RemoveAt(0);
            return packet;
        }
    }

    public void  Enqueue(Packet packet)
    {
        lock (packetsQ)
        {
            packetsQ.Add(packet);
            Monitor.Pulse(packetsQ);
        }
    }
}

现在我的线程写入队列中的数据包和线程读取队列中的读取。两者都是无限运行的线程。但我不知道如何在 packetQ.removeat(0) 处阻止线程写入。

4

1 回答 1

1

我认为您应该创建锁对象并将其用作您的锁

public class SynchronizedPacketQueue
   {
      [DataMember]
      public List<Packet> packetsQ;
      private object mylock = new object();

      public SynchronizedPacketQueue()
      {
        packetsQ = new List<Packet>();
      }

    public int Count
    {
        get { return packetsQ.Count; }
        private set{}
    }


    public Packet Dequeue()
    {
        lock (mylock)
        {
            if (packetsQ.Count == 0)
            {
                Monitor.Wait(mylock);

            }
            Packet packet = packetsQ[0];
            packetsQ.RemoveAt(0);
            return packet;
        }
    }

    public void  Enqueue(Packet packet)
    {
        lock (mylock)
        {
            packetsQ.Add(packet);
            Monitor.Pulse(mylock);
        }
    }
}
于 2012-07-04T07:05:30.697 回答