George George

George George

  • NA
  • 778
  • 0

thread safe in my code to manipulate List?

Apr 28 2008 12:03 AM

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