使用静态字典而不是会话asp.net mvc [英] using static Dictionary instead of session asp.net mvc

查看:163
本文介绍了使用静态字典而不是会话asp.net mvc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有session的序列化问题(如我所描述的 here )所以我使用静态字典而不是会话asp.net mvc

i have serialization problem with session(as i described here) so i used static Dictionary instead of session asp.net mvc

public static Dictionary<string, object> FlightDict;    
FlightDict.Add("I_ShoppingClient", client); 

在这种情况下,用户将覆盖它们的值?该
有什么问题,因为它们说静态变量用户数据可以被覆盖

in this case user will override their values?are there any problem with that because they says with static variable users data can be overrided

推荐答案

是的,你可以更改站点中的静态变量,但是你需要使用它来更改数据,但是在完成之前,您不需要锁定此数据。

Yes, you can change the static variables in the site, But You need to use this to change the data but that is not enough you need to lock this data until you have done.

public static Dictionary<string, object> CacheItems
    {
        get{ return cacheItems;  }    
        set{ cacheItems= value; }
    }

如何锁定?

您需要用于锁定所有添加或删除操作的方法,直到完成为止:

The approach you need to use to lock all actions of add or remove until you done is:

private static Dictionary<string, object> cacheItems = new Dictionary<string, object>();
private static object locker = new object();
public Dictionary<string, object> CacheItems
    {
        get{ return cacheItems; }   
        set{ cacheItems = value;}  
    }

YourFunction()
{  
  lock(locker)
  {
    CacheItems["VariableName"] = SomeObject;
  }  
}

用于处理您需要使用的应用程序状态的数据全局锁定 Application.Lock(); Application.UnLock(); 。即

for manipulating the data on application state you need to use the global lock of it Application.Lock(); and Application.UnLock();. i.e

Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"])+1;
Application.UnLock();

最后:避免应用程序状态,并使用静态变量来管理应用程序中的数据,从而实现更快的性能

Last: Avoid Application State and use the Static Variable to Manage the Data across the Application for Faster Performance

注意:您可以在此时添加一个锁,只有在您尝试更改之前删除它。

Note: you can add one lock at the time only so remove it before you are trying to change it

请记住:静态变量将在请求之间共享。此外,它们将在应用程序启动时被初始化,所以如果AppDomain,因此应用程序重新启动,它们的值将被重新初始化。

Keep in Mind : The static variables will be shared between requests. Moreover they will be initialized when application starts, so if the AppDomain, thus application gets restarted, their values will be reinitialized.

这篇关于使用静态字典而不是会话asp.net mvc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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