0
Answer

thread safe in my code to manipulate List?

George George

George George

16y
1.8k
1

Hello everyone,


Here is my code for review to see whether it is thread-safety. My question is, after remove the object instance from List buffer, I exit the lock synchronization block in method RemoveAndUseItem, is it thread safe to exit the lock synchronization and call method RemoveAndUseItem (method RemoveAndUseItem will only touch the removed instance)?

[Code]
        List<Foo> Buffer;
        object ListLock = new object();

        void AddItem(Foo f)
        {
            lock (ListLock)
            {
                Buffer.Add(f);
            }
        }

        void RemoveAndUseItem()
        {
            Foo LastItem;
            lock (ListLock)
            {
                LastItem = Buffer[Buffer.Count - 1];
                Buffer.RemoveAt(Buffer.Count - 1);
            }

            // no lock here? safe?
            SafeUseItem(LastItem);

            return;

        }

        void SafeUseItem(Foo f)
        {
            // use f here without synchronization control
        }
[/Code]


thanks in advance,
George