简体   繁体   中英

c# thread synchronization

I am developing an app for wp7. I required a synchronized read and write. So I created this class

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);
        }
    }
}

Now my threadwrite enqueues packets in the queue and threadread reads from the queue.Both are infinite running threads. But i don't know some how threadwrite is blocked at packetQ.removeat(0).

I think you should create lock object and use it your lock

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM