简体   繁体   中英

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?

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 your Get 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.

As long as the dictionary doesn't mutate (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM