asp.net缓存多线程锁的webpart [英] asp.net cache multithreading locks webparts

查看:106
本文介绍了asp.net缓存多线程锁的webpart的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情形:

假设我们有相同的数据操作两个不同的WebParts - 一个是饼图,另一种是数据表。
在他们的Page_Load他们异步从数据库中加载数据,当它在应用程序缓存为进一步利用或使用其他Web部件加载的地方。因此,每个ØWeb部件具有与此类似code:

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
       }
    }

由于双方的webpart对同一数据操作它没有任何意义,我两次执行code。

Since both webparts operate on the same data it does not make sense for me to execute the code twice.

什么是最好的办法有一个Web部件传达给其他的我已经获取数据那么就等到我把它放在高速缓存?

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 lock keyword to make sure that the data is loaded and added to the cache in an atomic manner.

更新:

我修改持有锁访问缓存的例子为尽可能短。而不是直接存储在所述缓存中的数据的一个代理将被代替存储。该代理将被创建并添加到缓存以原子方式。然后,代理将使用自己的锁定,以确保数据只装载一次。

I modified the example to hold the lock accessing Cache for 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.

protected void Page_Load(object sender, EventArgs e)
{ 
   string key = "dtMine" + "_" + Session["UserID"].ToString();

   DataProxy proxy = null;

   lock (Cache)
   {
     proxy = Cache[key];
     if (proxy == null)
     {
       proxy = new DataProxy();
       Cache[key] = proxy;
     }
   }

   object data = proxy.GetData();
}

private class DataProxy
{
  private object data = null;

  public object GetData()
  {
    lock (this)
    {
      if (data == null)
      {
        data = LoadData(); // This is what actually loads the data.
      }
      return data;
    }
  }
}

这篇关于asp.net缓存多线程锁的webpart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆