Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Say we have a class that is frequently used in a single-thread context: public c

ID: 644882 • Letter: S

Question

Say we have a class that is frequently used in a single-thread context:

public class Foo
{
    public List<Bar> Data;

    public virtual void ChangeData()
    {
        for(var i =0; i < Data.Count; i++)
        {
            if(i % 4 == 0)
            {
                data[i].Baz();
            }
        }
    }
}
If we were to decide we wanted to use the thread in a multi-threaded context (in addition to its current single-threaded usage), are there advantages (assuming it has full unit test coverage) to making a thread-safe subclass 'ThreadSafeFoo' vs. altering 'Foo' to be thread safe?

I was wondering about this because there are specific subclasses in System.Collections that are intended to be used across threads, and I wanted to know whether there was a reason this thread-safety wasn't simply rolled into List, etc.

Explanation / Answer

I was wondering about this because there are specific subclasses in System.Collections that are intended to be used across threads, and I wanted to know whether there was a reason this thread-safety wasn't simply rolled into List, etc.

In this specific example, it is because only a very limited subset of actions on say... Dictionary can be done performantly in ConcurrentDictionary. Subjecting all of your users to the overhead of synchronization (or the functionality limitations) is... not advised.

In the more general case, you should generally err towards using only one class. It reduces the complexity of your code. It is less code to maintain. It makes it easier for people to do "the right thing". Sometimes it's too onerous to provide the thread safety, and you get two classes. But if it's not, or it's close - just use the one.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote