开发者

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
{
    priva开发者_JS百科te 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?


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.


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?


After pondering this for the weekend, and after getting no further responses. I've decided the answer is: MS be crazy y'all. The whole point of offering a synchronize version of the object is for thread safety, yet a thread has no way at compile time to require a thread safe version of the object. The validation of this object has to take place at runtime, which is... bogus.

Thanks to everyone for their input. I appreciate it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜