c# - Locking across different threads in an ASP.NET WebAPI -


i've got scenario require cache information webapi temporarily when first called. same parameters api can called few times second.

due performance restrictions don't want each call fetching data , putting memory cache i've implemented system semaphores try , allow 1 thread initialize cache , allow rest query cache.

i've stripped down code show example of i'm doing currently.

      private static memorycacher memcacher = new memorycacher();       private static concurrentdictionary<string, semaphore> dictionary = new concurrentdictionary<string, semaphore>();                       private async task<int[]> doathing(string requesthash)       {                         // check existing cached result before hitting dictionary              var cachevalue = memcacher.getvalue(requesthash);              if (cachevalue != null)              {                                          return ((cachedresult)cachevalue).cheeseburgers;              }               semaphore semi;              semi = dictionary.getoradd(requesthash, new semaphore(1, 1, requesthash));                                semi.waitone();               //it's possible previous thread has filled cache. have squiz.              cachevalue = memcacher.getvalue(requesthash);              if (cachevalue != null)              {                                      dictionary.tryremove(requesthash);                         semi.release();                                  return ((cachedresult)cachevalue).cheeseburgers;                                         }               // fetch latest data relevant web api              var response = await httpclient.postasync(url, content);                                    // add result cache              memcacher.add(requesthash, new cachedresult() { cheeseburgers = response.returnarray }, datetime.now.addseconds(30));               // have added cacher don't need semaphore in dictonary anymore:              dictionary.tryremove(requesthash);               //open floodgates              semi.release()                return response.returnarray;       } 

unfortunately there many weird issues more 1 thread @ time manages through waitone() call , when released manages break due count restriction on semaphore. (to make sure 1 semaphore working @ time) i've tried using mutexes , monitors, since iis doesn't guarantee api call run on same thread causes fail regularly when mutex attempted released in different thread.

any suggestions on other ways implement welcome well!


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -