FYI: Using ArrayList.Synchronized on Derived Classes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mike Grasso

    #1

    FYI: Using ArrayList.Synchronized on Derived Classes

    I've seen a few messages on this, but no responses. Here's what I
    found out

    PROBLEM:
    How do you use ArrayList.Synch ronized to create thread-safe objects
    derived from ArrayList

    public class MyList : ArrayList
    {
    }

    // This throws an exception
    MyList list = (MyList)ArrayLi st.Synchronized (new MyList)


    ANSWER:
    You can't. ArrayList.Synch ronized returns a new ArrayList object.
    Sorry.

    THE (not so great) SOLUTION:
    Instead of deriving from ArrayList, Wrap it.

    public class MyList : IList
    {
    private ArrayList inner;
    public MyList()
    {
    inner = ArrayList.Synch ronized(new ArrayList);
    }

    // Implement the IList members using the inner ArrayList
    public object this[int index]
    {
    get
    {
    return inner[index];
    }
    set
    {
    inner[index] = value;
    }
    }

    You get the rest...
    If there is a better solution, post it!
Working...