Sign in to follow this  
Kaze

[.net] Is my collection threadsafe?

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this