0

Imagine I have an interface IHeapObject:

interface IHeapObject
{
    string Id {get;}
    SomeEnum Type {get;}
}

and it's implementation HeapObject:

class HeapObject : IHeapObject
{
    public string Id {get; private set;}

    public SomeEnum Type {get; private set;}

    public object objectLocker {get; } = new object();
}

Imagine I have a class that has a public IEnumerable<IHeapObject> Readonly-Property property. This property points to a private readonly IList<HeapObject> field. Like this:

class MyClass
{
    public IEnumerable<IHeapObject> Foo => _bar;

    private readonly IList<HeapObject> _bar;
}

Suppose the way I handle this collection inside of this class is 100% thread-safe. Furthermore, any and all state changes in the list and HeapObject itself happen only within this class. Is the fact that I'm exposing the collection a thread-safety concern?

My assumptions is that I can't guarantee that the IHeapObject instance will be "up-to-date" when read from outside MyClass. Meaning, as long as I don't rely on the properties' values for critical processes outside of it, I should be fine. Is this assumption correct?

Secondly, is there a risk of throwing an exception while iterating over the IEnumerable collection from outside of the class?

2
  • 1
    Why do you have public string Id {get; private set;} twice? Jan 27 '21 at 13:35
  • Thread safety and iteration-safe collection modification are related but different concepts. Problems (exceptions) involving the latter occur even with single threaded programming. Search "modify a collection while iterating".
    – Erik Eidt
    Jan 27 '21 at 15:04
1

The basic thread safety rules state that there can be multiple readers or a single writer, but not both at the same time.

You allow anyone to be a reader. You cannot control who is. Therefore, it is actually never safe to write to the structures.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.