
Untitled
By: a guest on
Dec 17th, 2010 | syntax:
C# | size: 1.27 KB | hits: 54 | expires: Never
public class CloseableThreadLocal {
[ThreadStatic]
public static Dictionary<int, object> slots;
private static readonly List<Dictionary<int, object>> slotsContainers = new List<Dictionary<int, object>>();
public static Dictionary<int, object> Slots {
get {
if (slots == null) {
var container = new Dictionary<int, object>();
slotsContainers.Add(container);
return slots = container;
}
return slots;
}
}
public /*protected internal*/ virtual Object InitialValue() {
return null;
}
public virtual Object Get() {
object val;
if (Slots.TryGetValue(this.GetHashCode(), out val)) {
return val;
}
val = InitialValue();
Set(val);
return val;
}
public virtual void Set(object val) {
Slots[this.GetHashCode()] = val;
}
public virtual void Close() {
if (slots != null)// intentionally using the field here, to avoid creating the instance
slots.Remove(this.GetHashCode());
}
~CloseableThreadLocal() {
foreach (var container in slotsContainers)
container.Remove(this.GetHashCode());
}
}