2016-09-20 15 views
0

我想緩存服務器中的一些靜態數據。如果任何用戶請求相同的數據緩存應該返回。緩存我的服務器中的所有用戶的靜態數據C#

如果我使用HttpContext.cache,它會因用戶而異。請幫助我如何在c#中做到這一點?

我曾嘗試:

HttpContext.Cache.Insert(cacheKey, Sonarresult, null, DateTime.Now.AddSeconds(Timeduration), Cache.NoSlidingExpiration); 

我想這也是所有用戶將存儲到緩存中。我不想那樣。第一個用戶只需要存儲它。

+0

[使用應用程序緩存。(https://msdn.microsoft.com/en-us/library/ms178597.aspx) –

+0

你能解釋一下我該怎麼做? – Raj

回答

1

像使用會話變量一樣使用應用程序緩存可以爲您解決問題。

例如

// get 
string message = Application["somemessage"].ToString(); 

對所有用戶都是一樣的。

要進一步闡述,請小心在代碼中爲應用程序變量設置值的位置,因爲一旦它們發生更改,它們將全部更改。

// set 
Application["somemessage"] = "your message"; 

的Global.asax將是一個可能的地方設置應用程序變量的值,如果他們永遠不會改變:

void Application_Start(object sender, EventArgs e) 
{ 
    // Code that runs on application startup 

    // here we set the value every time the application starts 
    Application["somemessage"] = "your message"; 

    // the following line will get the SiteName from the web.config setting section 
    Application["SiteName"] = ConfigurationManager.AppSettings["SiteName"].ToString(); 
} 
0

可以使用應用程序緩存來做到這一點。

void Application_Start() 
    { 
     _cache = Context.Cache; 
     _cache.Insert ("mycahce", mystaticvariabledata, null, 
     Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, 
     CacheItemPriority.Default,null); 
    } 
相關問題