views:

416

answers:

4

I want to add items to a list from one thread and from another thread remove items from the same list. However, I am not sure if I will run into problems with multiple threads accessing the same object. I have read a bit on the lock statement but I am not sure how to implement this. In short, the question is, how do I ensure thread safe access to my list.

A: 

All add and remove operations must be done through the wrapper returned by the Synchronized method.

adatapost
+4  A: 

Use the SyncRoot into IList:

lock(SomeList.SyncRoot) {...}
Chernikov
I don't think IList has a SyncRoot does it? It's just ArrayLists?
Russell Troywest
Yes it does. It's an Explicit Interface Implementation. ((IList)someList).SyncRoot
bruno conde
A: 

Here is an EXTREMELY rough example of locking. Both threads are now safe when adding and removing from the list. This is not an example of how to create and use threads - just an example of how to use lock.

  Class A{
            private List<int> _list = new List<int>();

            private void DoOtherThreadWork() {
                while (true) {
                    //so something with thread. Sleep it, whatever...
                    lock(_list) {
                        _list.Add(1);
                    }
                }    
            }

            private void StartWorking(object sender, EventArgs e) {
                Thread worker = new Thread(DoOtherThreadWork);
                worker.Start();

                while (true) {
                    lock(_list) {
                        if (_list.Count > 0) {
                            _list.RemoveAt(0);
                        }
                    }
                }
            }
    }

I should probably also add that for anything more complicated than this basic example you might want to use a different object to the list itself.

private object lockObj = new Object();
        private void DoOtherThreadWork() {
                while (true) {
                    //so something with thread. Sleep it, whatever...
                    lock(_lockObj ) {
Russell Troywest
+1  A: 

If you're doing a producer/consumer system -- and it sounds like you are -- a synchronized Queue sounds like the more appropriate structure, rather than a List.

Steve Gilham