I have following scenario:
Lets say we have two different webparts operating on the same data – one is a pie chart, another is a data table.
in their Page_Load they asynchronously load data from the database and when loaded place it in application cache for further use or use by other web parts. So each o the web parts has code similar to this:
protected void Page_Load(object sender, EventArgs e)
{
if (Cache["dtMine" + "_" + Session["UserID"].ToString()]==null)
{
...
Page.RegisterAsyncTask(new PageAsyncTask(
new BeginEventHandler(BeginGetByUserID),
new EndEventHandler(EndGetByUserID),
null, args, true));
}
else
{
get data from cache and bind to controls of the webpart
}
}
Since both webparts operate on the same data it does not make sense for me to execute the code twice.
What is the best approach to have one web part communicate to the other “i am already fetching data so just wait until i place it in cache”?
I have been considering mutex, lock, assigning temporary value to the cache item and waiting until that temporary value changes… many options – which one should I use.
You will want to take advantage of the
lockkeyword to make sure that the data is loaded and added to the cache in an atomic manner.Update:
I modified the example to hold the lock accessing
Cachefor as short as possible. Instead of storing the data directly in the cache a proxy will be stored instead. The proxy will be created and added to the cache in an atomic manner. The proxy will then use its own locking to make sure that the data is only loaded once.