【问题标题】:cache problem in asp.net with c#使用 c# 在 asp.net 中的缓存问题
【发布时间】:2010-12-14 03:52:54
【问题描述】:

我正在使用 fileuplaod 控件来上传图片。为此,我曾经将其存储在缓存中

以字节格式显示 2 小时,并使用 .ashx 文件中的 HttpContext 显示此图像。出于某种原因

有时会保存在缓存中,有时不会。我正在使用 asp.net 2.0 和 C# 语言。

我的保存代码:

//Name of the Image 
string strGuid = Guid.NewGuid().ToString(); 
byte[] byteImage = new byte[ImageUpload.PostedFile.ContentLength];

//file upload control ID "ImageUpload" and read it and save it in cache.
ImageUpload.PostedFile.InputStream.Read(byteImage, 0, byteImage.Length);

//Saving Byte in the cache
Cache.Add(strGuid, byteImage, null, DateTime.Now.AddDays(2), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

//Saving Image Format in cache
Cache.Add(string.Format("{0}_Type", strGuid), strContentType, null, DateTime.Now.AddDays(2), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
UserImage.ImageUrl = string.Format("~/UserControl/ImageHander.ashx?imgId={0}", strGuid);

使用 .ashx 文件渲染图像的代码:

public void ProcessRequest (HttpContext context) 
{
    string strImageGuid = context.Request.QueryString["imgId"].ToString();
    string strContentTypeID = string.Format("{0}_Type",  context.Request.QueryString["imgId"].ToString());
    byte[] byteImage =(byte []) context.Cache[strImageGuid];
    string strContentType = (string)context.Cache[strContentTypeID];
    context.Response.ContentType = strContentType;
    context.Response.OutputStream.Write(byteImage, 0, byteImage.Length);
}

将字节图像保存在缓存中是否有任何问题或任何其他更好的方法?

谢谢! 桑杰朋友

【问题讨论】:

    标签: c# asp.net httpcontext httpcontext.cache


    【解决方案1】:

    您可以指定 CacheItemPriority.NotRemovable 而不是 CacheItemPriority.Normal 以防止它在过期之前从缓存中删除。

    但更传统的方法是允许将其删除,并在您发现它丢失时重新填充缓存。

    【讨论】:

      【解决方案2】:

      不能保证在缓存中找到放入缓存的项目。在某些情况下,框架可能会使缓存中的项目过期,例如,如果它开始内存不足。在这种情况下,它将调用您在将项目添加到缓存时传递的onRemoveCallback

      缓存不是可靠的存储,您需要在使用它之前始终检查项目是否存在,如果它没有执行必要的操作来获取它并将其放回那里,以便将来的调用者可以找到它。

      【讨论】:

        猜你喜欢
        • 2011-02-28
        • 2011-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        • 2011-08-01
        相关资源
        最近更新 更多