Reputation: 11330
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
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
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