Couldn't think of a better title for this but here goes:
Wanted something similar to the Web Session for use in WinForm apps but didn't want to go overboard. Hopefully this is a thread safe implementation. Not sure though:
use in your code like this:
AppState appState = AppState.GetAppState();
appState.Cache["test"] = "Hello";
// or
AppState.GetAppState().Cache["test"] = "Hello";
// then later on...
string data = AppState.GetAppState().Cache["test"].ToString();
Here is the code for the AppState:
using System;
using System.Collections;
namespace Development
{
public class AppState
{
private static AppState _appState;
private Hashtable _cache;
private Hashtable _syncCache;
private AppState()
{
_cache = new Hashtable();
_syncCache = Hashtable.Synchronized( _cache );
}
public Hashtable Cache
{
get { return _syncCache; }
}
public static AppState GetAppState()
{
// Support multithreaded applications through
// "Double checked locking" pattern which avoids
// locking every time the method is invoked
if( _appState == null )
{
// Only one thread can obtain a mutex
using( System.Threading.Mutex mutex = new System.Threading.Mutex() )
{
mutex.WaitOne();
if( _appState == null )
_appState = new AppState();
mutex.Close();
}
}
return _appState;
}
}
}
posted @ Tuesday, February 01, 2005 12:17 PM