cache problem in asp.net with c#
I am using the fileuplaod control to upload the images. For this I used to stored it in the cache
for 2 hours in byte format and show this image using the HttpContext in the .ashx file. For some Reason it
is sometime saving in the cache and sometime not. I am using asp.net 2.0 and C# language.
My code For Saving :
//Name of the Image
string strGuid = Guid.NewGuid().ToString();
byte[] byteImage = new byte[ImageUpload.PostedFile.ContentLength];
//file开发者_C百科 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);
Code For Rendering Image using .ashx file:
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);
}
Is there any Problem In saving the byte image in cache Or any other better way of doing this?
Thanks! sanjay pal
Items put in a cache are not guaranteed to be found there. In some situations the framework might expire items from the cache, for example if it starts running low on memory. In this case it will call the onRemoveCallback you pass along when you add an item to the cache.
The cache is not a reliable storage, you need to always check if the item is there before using it and if it is not perform the necessary actions to fetch it and put it back there so that future callers could find it.
You could specify CacheItemPriority.NotRemovable instead of CacheItemPriority.Normal to prevent it being removed from the Cache before its expiration is up.
But a more conventional approach is to allow it to be removed, and repopulate the cache if you find it's missing.
精彩评论