Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 基于静态变量和MVC的缓存方法_C#_Caching_Model View Controller_Static_Entity - Fatal编程技术网

C# 基于静态变量和MVC的缓存方法

C# 基于静态变量和MVC的缓存方法,c#,caching,model-view-controller,static,entity,C#,Caching,Model View Controller,Static,Entity,我正试图在我的MVC页面上实现一些缓存方法,如下所示 private static List<T> DATA = new List<T>() public ActionResult Index() { if(DATA.Count()==0) { FillGlobalVaribles(); } } public JsonResult GC() {

我正试图在我的MVC页面上实现一些缓存方法,如下所示

    private static List<T> DATA = new List<T>()

    public ActionResult Index()
    {
         if(DATA.Count()==0)
          {
          FillGlobalVaribles();
          }
    }

    public JsonResult GC()
    {
         DATA = new List<T>();
    } 

    private static FillGlobalVariables()
    {
        DATA = entityObject.foo.ToList();
    }

   public JsonResult ListItems(string FilterString)
    {
      DATA.OrderBy(c=>c.ID).ToList();
     return Json(new {Result="OK",RecordSet = Data});
    }
私有静态列表数据=新列表()
公共行动结果索引()
{
if(DATA.Count()==0)
{
FillGlobalVaribles();
}
}
公共JsonResult GC()
{
数据=新列表();
} 
私有静态FillGlobalVariables()
{
DATA=entityObject.foo.ToList();
}
公共JsonResult列表项(字符串过滤器字符串)
{
DATA.OrderBy(c=>c.ID).ToList();
返回Json(新的{Result=“OK”,RecordSet=Data});
}
我在控制器的索引方法中填充静态变量。若用户进行一些排序,一些过滤器将应用于数据变量

如果用户更改页面(单击另一个标记)对GC方法的ajax调用并清除变量,我将实现自定义GC方法

所以我的问题是,


如果数据变量已填充并应用了一些筛选(例如:纯数据变量包含3000项,筛选结果为200项),并且另一个用户来到页面,则数据变量包含200项。但是我想为每个用户创建新的对象实例。

使用此类静态时需要小心。除非使用lock{}语句或互斥体,否则几个不同的线程可以尝试同时初始化或使用列表。如果你不小心的话,最后会弄得一团糟

看看Redis,它可能会为你提供你所需要的东西

Redis是一种内存缓存,可用于存储单个项目和列表。下面是一个小例子:

using StackExchange.Redis;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace RedisTest
{

    class Program
    {

        #region Diagnostics

        static void w(string msg = "")
        {
            System.Console.WriteLine(msg);
        }

        static void w(string fmt, params object [] p)
        {
            string msg = string.Format(fmt, p);
            w(msg);
        }

        #endregion Diagnostics




        //
        // Use of redis:
        //
        // https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md
        // https://redis.io/commands
        //


        static string string_key = "key_string";
        static string string_val = "Mary had a little lamb. She ate it.";

        static string int_key = "key_int";
        static string int_val = "100";

        static string non_existent_key = "sdlfhsfhshdfhsdf";


        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            w("Connected to Redis.");
            w();

            IDatabase redis_db = redis.GetDatabase();

            // Storage and retrieval of a string
            redis_db.StringSet(string_key, string_val);
            var redis_val = redis_db.StringGet(string_key);
            string sval = (string) redis_val;
            w("String value retrieved: {0}", sval);


            // Storage of an int; decrementing and incrementing it
            redis_db.StringSet(int_key, int_val);
            redis_db.StringDecrement(int_key, 15);
            redis_val = redis_db.StringGet(int_key);
            int iVal = (int)redis_val;
            w("Int retrieved: {0}", iVal);

            redis_db.StringIncrement(int_key, 55);
            redis_val = redis_db.StringGet(int_key);
            iVal = (int)redis_val;
            w("Int retrieved: {0}", iVal);


            // Retrieving a non-existent value
            redis_val = redis_db.StringGet(non_existent_key);
            if (redis_val.IsNull)
            {
                w("Null value retrieved.");
            }


            // Check for existence of a key

            bool b = redis_db.KeyExists(int_key);
            if (b)
            {
                w("Key {0} exists.", int_key);
            }

            b = redis_db.KeyExists(non_existent_key);
            if (!b)
            {
                w("Key {0} does not exist.", int_key);
            }




            // Delete a key
            redis_db.KeyDelete(string_key);
            redis_db.KeyDelete(int_key);

            // Delete all keys - only available from command line: https://redis.io/commands/flushdb


            w();
            redis.Close();
            redis.Dispose();
            w("Disconnected from Redis.");

            w();
            w("Hit RETURN to end.");
            System.Console.ReadLine();
        }

    } // class Program

} // namespace RedisTest
它的美妙之处在于,如果您有多台服务器运行您的网站,那么使用它可以在所有服务器之间缓存相同的数据。因此,多线程访问同一数据的所有担忧都由您来处理

希望这有帮助


亚当。

你好。谢谢你回答我的问题。我尝试使用lock{}语句,但我认为它不起作用。如何使用lock语句?你能给点样品吗?我试过redis,但我不了解redis的工作原理。嗨,Toygar。一般来说,如果你能帮助MVC,你会更好地避开静力学。我不能说永远不要使用它们,但要先寻找其他方法。我编辑了我的原始答案,加入了一个使用Redis的小例子-注意,你必须先安装它。嗨,亚当,我已经知道Redis示例了,谢谢分享。但是我如何在redis上存储我的列表呢?比如redis.push(Listdata);嗯,你不能直接向它发送列表。您需要为此编写自己的助手方法。但是在元素中循环并使用诸如和@ProfK Hi之类的命令。若我们查找数据,但数据不在那个里,我们通常会用数据填充redis。那么,一个数据请求进来了,是在redis中吗?否->计算数据(通常从db加载)并将其发送到redis。是->从redis加载。无论哪种方式,都会将数据作为结果发送回客户端。如果发生任何改变数据的情况,请告诉redis将其删除,以便下次重新计算。