• Advertisement
Sign in to follow this  

[.net] Is my collection threadsafe?

This topic is 3357 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What the title says, Is this a valid solution for a multi-threaded producer consumer problem
    public class Pipe<Type>
    {

        public Pipe() { 
        
        }
        Queue<Type> objs = new Queue<Type>();

        public void PushObject(Type obj) {
            lock (objs)
            {
                objs.Enqueue(obj);
            }
        }


        public Type[] GetObjects(int max)
        {
            lock (objs)
            {
                List<Type> list = new List<Type>();
                
                while (list.Count < max && objs.Count > 0){
                    list.Add(objs.Dequeue());
                }

                return list.ToArray();
            }
        }
    }


Share this post


Link to post
Share on other sites
Advertisement
Yeah, assuming this is the only place "objs" is being used. You can even move the list creation and return outside of the lock, leaving only the list.Add part.

Share this post


Link to post
Share on other sites
thanks, I just wanted to make sure I was using lock() correctly

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement