dotnetnoob
dotnetnoob

Reputation: 11330

How do I make this c# property threadsafe?

I have a few library utilities which make things a little simpler.

        public static RequestUow Uow
        {
            get { return ContextItemsHelper.Get<RequestUow>("Uow"); }
            set { ContextItemsHelper.Set<RequestUow>("Uow", value); }
        }

And in ContextItemsHelper

    public static T Get<T>(string key)
    {
        Guard.NullOrEmpty(key, "key");

        object obj = Items[key];

        return obj.IsNotNull() ? (T)obj : default(T);
    }

    static IDictionary Items { get { return HttpContextHelper.Current.Items; } }

This works fine but i now want to check if the property uow is null, if it is set a new RequestUow and return it.

The examples I've seen involve setting your own member variable, however i'm wondering if this is likely to be threadsafe.

Anyone got any advice or solutions to offer?

Upvotes: 1

Views: 142

Answers (3)

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

Make Items a ConcurrentDictionary and use it's AddOrUpdate method. As the collection itself is thread safe, you won't have to care about it.

It would also be better if yourGet changed to something like this:

public static T Get<T>(string key)
{
    Guard.NullOrEmpty(key, "key");
    return Items.GetOrAdd( key, (key) => default(T) );
}

This way the defaults are added at first try and just returned if they are called again.

Upvotes: 3

Lucero
Lucero

Reputation: 60190

As long as the dictionary doesn't mutate (e.g. no updates), access it is fully threadsafe without any additional measures (*).

Note that it doesn't help to have threadsafe getter/setters for the dictionary if the items contained aren't threadsafe themselves. The safest bet is to use immutable items in the dictionary; if your RequestUow objects are mutable, then you need to make them (and everything else that might be retrieved using this dictionary) threadsafe as well.

*: See for instance this PDF for information on thread-safe collections in .NET. Page 18 clarifies that read-only access does not need additional measured for thread safety.

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13450

use pattern Double checked locking pattern

Upvotes: 0

Related Questions