C# 将文件数据加载到静态类、将文件加载到缓存或其他选项?
我正在使用PO文件本地化ASP.NET MVC 5应用程序 我创建了一个HTTP模块,用于将html、javascript等类型的响应相交:C# 将文件数据加载到静态类、将文件加载到缓存或其他选项?,c#,asp.net-mvc,C#,Asp.net Mvc,我正在使用PO文件本地化ASP.NET MVC 5应用程序 我创建了一个HTTP模块,用于将html、javascript等类型的响应相交: public class I18NModule : IHttpModule { private Regex _types; public I18NModule() { _types = new Regex(@"^(?:(?:(?:text|application)/(?:plain|html|xml|javascript|
public class I18NModule : IHttpModule {
private Regex _types;
public I18NModule() {
_types = new Regex(@"^(?:(?:(?:text|application)/(?:plain|html|xml|javascript|x-javascript|json|x-json))(?:\s*;.*)?)$");
} // I18NModule
public void Init(HttpApplication application) {
application.ReleaseRequestState += OnReleaseRequestState;
} // Init
public void Dispose() {
} // Dispose
private void OnReleaseRequestState(Object sender, EventArgs e) {
HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
if (_types != null && _types.Match(context.Response.ContentType).Success)
context.Response.Filter = new I18NFilter(context, context.Response.Filter, _service);
} // Handle
} // I18NModule
然后我有一个i18n过滤器,如下所示:
public class I18NFilter : MemoryStream {
private II18NNuggetService _service;
protected HttpContextBase _context;
private MemoryStream _buffer = new MemoryStream();
protected Stream _output;
public I18NFilter(HttpContextBase context, Stream output, II18NNuggetService service) {
_context = context;
_output = output;
_service = service;
} // I18NFilter
public override void Write(Byte[] buffer, Int32 offset, Int32 count) {
_buffer.Write(buffer, offset, count);
} // Write
public override void Flush() {
Encoding encoding = _context.Response.ContentEncoding;
Byte[] buffer = _buffer.GetBuffer();
String entity = encoding.GetString(buffer, 0, (Int32)_buffer.Length);
_buffer.Dispose();
_buffer = null;
buffer = null;
*USE SERVICE TO LOAD PO FILE AND PROCESS IT*
buffer = encoding.GetBytes(entity);
encoding = null;
Int32 count = buffer.Length;
_output.Write(buffer, 0, count);
_output.Flush();
} // Flush
} // I18NFilter
当我与响应相交时,我查找字符串为[[[某些文本]]]。“一些文本”将是关键,我将在当前线程语言的PO文件中寻找
因此,我需要加载当前语言的PO文件,对其进行处理,并找到需要翻译的字符串
我的问题是性能。。。我应该在静态类中加载整个文件吗
我应该在每个请求和使用中加载文件吗
我应该怎么做呢?因为这是一个我可以利用的HTTP应用程序。下面是一个如何使用它来最小化性能成本的示例:
public override void Flush() {
...
var fileContents = GetLanguageFileContents();
...
}
private string GetLanguageFileContents(string languageName) {
if (HttpRuntime.Cache[languageName] != null)
{
//Just pull it from memory!
return (string)HttpRuntime.Cache[languageName];
}
else
{
//Take the IO hit :(
var fileContents = ReadFileFromDiskOrDatabase();
//Store the data in memory to avoid future IO hits :)
HttpRuntime.Cache[languageName] = fileContents;
return fileContents;
}
}
但是,如果我将fileContents保存到一个类的静态属性中,这会与使用缓存具有相同的效果吗?这是我不确定的事情…@MDMoura抱歉,我没有看到你的回复。我想看看这个问题,这将有助于澄清关于ASP.NET的静态类混淆:我正在阅读您提到的线程。文件中的翻译对于所有用户都是相同的。这不符合静态类的条件吗?当然,静态类将在所有请求中都保留在内存中,而不考虑用户。