Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Dec 17th, 2010  |  syntax: C#  |  size: 1.27 KB  |  hits: 54  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. public class CloseableThreadLocal {
  2.     [ThreadStatic]
  3.     public static Dictionary<int, object> slots;
  4.  
  5.     private static readonly List<Dictionary<int, object>> slotsContainers = new List<Dictionary<int, object>>();
  6.  
  7.     public static Dictionary<int, object> Slots {
  8.         get {
  9.             if (slots == null) {
  10.                 var container = new Dictionary<int, object>();
  11.                 slotsContainers.Add(container);
  12.                 return slots = container;
  13.             }
  14.  
  15.             return slots;
  16.         }
  17.     }
  18.  
  19.     public /*protected internal*/ virtual Object InitialValue() {
  20.         return null;
  21.     }
  22.  
  23.     public virtual Object Get() {
  24.         object val;
  25.  
  26.         if (Slots.TryGetValue(this.GetHashCode(), out val)) {
  27.             return val;
  28.         }
  29.         val = InitialValue();
  30.         Set(val);
  31.         return val;
  32.     }
  33.  
  34.     public virtual void Set(object val) {
  35.         Slots[this.GetHashCode()] = val;
  36.     }
  37.  
  38.     public virtual void Close() {
  39.         if (slots != null)// intentionally using the field here, to avoid creating the instance
  40.             slots.Remove(this.GetHashCode());
  41.     }
  42.  
  43.     ~CloseableThreadLocal() {
  44.         foreach (var container in slotsContainers)
  45.             container.Remove(this.GetHashCode());
  46.     }
  47. }