c# - Locking a static field -
i'm maintaining application consumes common library has static instance of class(classwrapper). class wrapper around microsoft patterns , practices's cachemanager (v3.1 of el)
the library hosted in web application , in windows service app, (both inherently multi threaded) there bunch of places in app invokes add method on wrapper in turn calls add on cache manager add item cache manager.
as understand, cachemanager not thread safe , cachewrapper not perform locking ensure thread safety in call add.
i cannot modify library code directly add synhronization code , considering writing helper method , modifying call sites use helper instead of calling add on wrapper directly.
class cachehelper { private static object _synclock = new object(); public static void add<t>(cachewrapper wrapper, string key, t value, int expireinmins) { lock (_synclock) { wrapper.add(key, value, expireinmins); } } }
do see problems approach. i'm bit weary since cachewrapper static , hence inherently _synclock. feel bit uneasy locking on static objects, don't have of choice since cachewrapper static instance exposed throughout process space of host (web app , windows service).
any advice or vote of confidence appreciated.
i not sure cachemanager being not thread-safe. check this msdn article - states clearly:
every method call made through cachemanager object thread safe.
now, coming implementation, not why passing cachewrapper instance methods. cachewrapper being static instance can refer directly such as
class cachehelper { private static cachewrapper getwrapper() { return [lib namespace].[class name].[field name referring cachewrapper]; } public static void add<t>(string key, t value, int expireinmins) { var wrapper = getwrapper(); lock (wrapper) { wrapper.add(key, value, expireinmins); } } ...
again, getwrapper factory method , implementation can change - can use static delegate cachewrapper instance or use dependency injection reference cachewrapper.
another advantage here if there multiple instances cachewrapper take lock on 1 using currently.
Comments
Post a Comment