本文實例講述了asp.net模板引擎Razor中cacheName的問題。分享給大家供大家參考。具體如下:
一、為什么使用cacheName
使用cacheName主要是考慮到Razor.Parse()每解析一次都會動態(tài)創(chuàng)建一個程序集,如果解析量很大,就會產生很多程序集,大量的程序集調用會造成程序非常慢。
舉個例子:
如果編譯1000次,編譯速度就會很慢。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
static void Main( string [] args) { string cshtml = File.ReadAllText( @"E:\百度云同步盤\Study\Net_ASP.NET\Web基本原理\RazorCacheNameTest\HTMLPage1.cshtml" ); for ( int i = 0; i < 1000; i++) { string html = Razor.Parse(cshtml); } Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly asm in asms) { Console.WriteLine(asm.FullName+ "\r\n" ); } Console.ReadKey(); } |
二、如何解決這個問題
使用Razor.Parse()時,帶上cacheName參數。
指定一個cacheName叫cc,下次Parse()解析時就不會重新編譯了(除非cshtml內容修改,那么cacheName名也要重新命名,讓Parse()解析新文件)
1
2
3
4
5
6
7
8
9
|
for ( int i = 0; i < 1000; i++) { //如果調用1000次,使用下面方式就會創(chuàng)建很多程序集,性能很低 string html = Razor.Parse(cshtml); //解析的cshtml文件我給的一個“緩存名”是cc,這次一旦編譯成功 //下次再讓你Parse() cc就不用重復編譯了,速度會非常快, //除非cshtml內容修改 Razor.Parse(cshtml, null , "cc" ); } |
三、怎么確定cacheName表示的文件已修改呢?
有兩種方式,一種就是文件全路徑+文件修改時間,還可以根據cshtml文件的MD5值。
1
2
3
4
5
6
7
8
9
|
for ( int i = 0; i < 10; i++) { string cshtml = File.ReadAllText(fullPath); string cacheName = fullPath + File.GetLastWriteTime(fullPath); //文件全路徑+文件上一次被修改時間 string html = Razor.Parse(cshtml, null ,cacheName); Console.WriteLine(html); Console.ReadKey(); } |
每當cshtml文件被修改,cacheName的值就會改變,Parse()根據cacheName值判斷是否重新編譯。假如測試過程中對cshtml文件做了三次修改,最終會生成三個程序集,如果cshtml文件未修改,最后只有一個程序集。
注意:關于cacheName的問題。
經過試驗發(fā)現,即使cacheName寫成一個固定的值,當cshtml發(fā)生改變的時候Parse的結果也是修改后的內容,這是為什么呢?
經過反編譯我們發(fā)現Parse方法最終調用的是TemplateService的GetTemplate方法,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
private ITemplate GetTemplate<T>( string razorTemplate, object model, string cacheName) { Func< string , CachedTemplateItem, CachedTemplateItem> updateValueFactory = null ; CachedTemplateItem item; if (razorTemplate == null ) { throw new ArgumentNullException( "razorTemplate" ); } int hashCode = razorTemplate.GetHashCode(); if (! this ._cache.TryGetValue(cacheName, out item) || (item.CachedHashCode != hashCode)) { Type templateType = this .CreateTemplateType(razorTemplate, (model == null ) ? typeof (T) : model.GetType()); item = new CachedTemplateItem(hashCode, templateType); if (updateValueFactory == null ) { updateValueFactory = (n, i) => item; } this ._cache.AddOrUpdate(cacheName, item, updateValueFactory); } return this .CreateTemplate( null , item.TemplateType, model); } |
代碼大意是:從緩存cache中查找是否有名字等于cacheName的緩存項“TryGetValue(cacheName, out item)”,如果不存在,則編譯創(chuàng)建;如果存在,則再檢查緩存中的cshtml內容的hashCode(字符串的特征碼,相同的字符串的HashCode一樣,不同字符串的HashCode有一樣的概率)和這次傳進來的razorTemplate的HashCode是否一樣,如果不一樣也重新編譯創(chuàng)建,而不使用緩存的。
因此這就能解釋為什么用一個固定的cacheName,只要修改cshtml的內容,還是會Parse出新內容了。
有同學會問:既然修改cshtml后,就會重新Parse新內容,那要cacheName還有什么意義呢?這是因為不同的字符串的HashCode相同的概率很低,但并不是沒有“A、B兩個字符串不一樣,但是hashcode相同”這種可能,因此如果只依賴HashCode的話,那么有這樣的概率“cshtml的文件修改了,但是恰好修改后的HashCode和修改以前是一樣的,那么Parse還是執(zhí)行舊的邏輯”。所以加上cacheName才是“雙保險”。
希望本文所述對大家的asp.net程序設計有所幫助。