Thursday, March 22, 2012

Waiting for a method to execute

I have a DAL and a method which caches a dataset . This method takes 5-7 seconds to finish. The problem is when app needs to re-populate cache and say 10 requests come at the same time, each request begin to populate same cache object (because cache==null) and 10*SQL server call occures. What I would like to do is when caching begins my method informs requests that its in progress so requests wait for this method to finish it job. So there will be one call to SQl server. Any ideas how to achieve this? Thanks and regards.

Hi,

basically web requests in ASP.NET happen on separate threads, so you can use threading mechanisms. E.g locks (lock statement in C#, SyncLock in VB.NET). With them you can create a statement which is executed only by one thread at given time. Basically make the loading of cache happen only on one thread, so that others won't try doing it. It justhas the drawback that all requests are suspended while the cache loads.

Another way would be serving requests with old data as far as the new is getting loaded (using cache callback for repopulating data and if original cache item is nothing, serving from the "spare" item as long as item is getting loaded with fresh data)


Thanks for your replay. It helped me much.

For those who are interested in this topic, I figured it out using Monitor.TryEnter, insted of Lock, beacuse it accepts time-out parameter.

Thanks again joteke you gave me a good starting point.

0 comments:

Post a Comment