AppDomain.GetData
should not be used for caching purposes. Instead use solutions like System.Runtime.Caching
. Or even just a static ConcurrentDictionary
will be better.
If you insist on using AppDomain
to store the values you should never delete everything in it - it stores information required by .NET framework to run properly.
Either store your values in a dictionary inside the AppDomain
object or keep a list of keys yourself.
A simple in memory cache using a static dictionary (the second approach is for .NET 2.0 with explicit locks - note that this is very simple solution, there are better alternatives to locking):
using System;
using System.Collections.Concurrent;
namespace YourNamespace
{
public static class ObjectCache
{
private readonly static ConcurrentDictionary<string, object> Data = new ConcurrentDictionary<string, object>();
public static void SetValue(string key, object value)
{
Data[key] = value;
}
public static object GetValue(string key)
{
object t;
if (!Data.TryGetValue(key, out t))
return null;
return t;
}
public static void Purge()
{
Data.Clear();
}
}
public static class ObjectCache2
{
private readonly static Dictionary<string, object> Data = new Dictionary<string, object>();
public static void SetValue(string key, object value)
{
lock (Data)
Data[key] = value;
}
public static object GetValue(string key)
{
object t;
lock (Data)
{
if (!Data.TryGetValue(key, out t))
return null;
}
return t;
}
public static void Purge()
{
lock (Data)
Data.Clear();
}
}
}