Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of this .Net pattern

I was looking for a pattern to be able to provide both a thread-safe and unsafe version of the same class. The technical aspects of this are pretty obvious. I guess was hoping to find naming/access conventions etc...

So I find this pattern everywhere in the 'Systems.Collections' namespace:

public class WhatEv
{
    private class SyncWhatEv : WhatEv
    {
        // overrides IsSyncronized = true
        // overrides whatever else to make it thread safe
    }

    public virtual bool IsSynchronized
    {
        get { return false; }  
    } 

    public static WhatEv Synchronized(WhatEv whatEv)
    {
        return new SyncWhatEv(whatEv);
    }
}

There are a number of classes that implement this: HashTable, Queue, ArrayList, Stack, etc... I understand the inheritance. But why make it a private, nested class and make the user jump through a hoop to get to it? Are there any benefits to doing it this way?

like image 755
TBone Avatar asked Oct 11 '22 07:10

TBone


2 Answers

In most cases, a thread-safe version of the object (i.e. Hashtable, Queue) is not needed. Therefore, it doesn't make sense to add the overhead needed to make it thread-safe by default. Using the Synchronized method, allows users that need thread-safety to get a thread-safe version.

The synchronized version of the object doesn't add any additional functionality, other than thread-safety. They don't expose any new members, nor does knowing their underlying type really help. So they are made private and simply "look" like their public/base class.

like image 109
CodeNaked Avatar answered Dec 17 '22 19:12

CodeNaked


In theory, this is a good idea, and @CodeNaked has a good explanation. In practice, there are still problems with this. For example, if you need to make 2 calls into your thread-safe class and need thread safety for both calls combined, you still need to do a lock. Good explanation in this SO item: In C# would it be better to use Queue.Synchronized or lock() for thread safety?

like image 27
Joel Rondeau Avatar answered Dec 17 '22 19:12

Joel Rondeau