使用异步缓存来保证高流量网页及时更新与低错误率(4)
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="item">缓存对象</param>
public static void saveCache(CacheItem item)
{
string mCacheName = item.CacheName + "_memory";
string fCacheName = item.CacheName + "_file";
Thread memoryCache = getThread(mCacheName);
Thread fileCache = getThread(fCacheName);
if (memoryCache == null)
{
memoryCache = new Thread(new ParameterizedThreadStart(UpdateCache));
memoryCache.IsBackground = true;
memoryCache.Start(item);
}
if (fileCache == null)
{
fileCache = new Thread(new ParameterizedThreadStart(UpdateFile));
fileCache.IsBackground = true;
fileCache.Start(item);
}
lockx.EnterWriteLock();
try
{
threadTable[mCacheName] = memoryCache;
threadTable[fCacheName] = fileCache;
}
catch { }
finally { lockx.ExitWriteLock(); }
}
public static string readCacheContent(CacheItem item)
{
//Stopwatch watch = new Stopwatch();
//watch.Start();
string content = readCache(item.CacheName);
if (content==null || content.Length < 0)
{
content = readFile(item.CacheName);
saveCache(item);
}
//读取缓存失败
if (content != null && content.Length <= 0)
{
//throw (new Exception("读取内容失败:" + item.CacheName));
content = item.doProcess();
//saveCache(item);
}
return content;
//watch.Stop();
//content += ("\r\n<!--方法执行时间:" + watch.ElapsedMilliseconds + "-->\r\n");
}
#endregion
#region 公共处理
public static string saveCache(string cacheName, ProcessDataDelegate mainMathod, object[] args)
{
using (CacheItem tmpCache = new CacheItem())
{
tmpCache.CacheName = cacheName;
tmpCache.CacheDelegate = mainMathod;
tmpCache.CacheArgs = args;
string content = "";
content = readCacheContent(tmpCache);
return content;
}
}
#endregion
}
现在给一个使用的例子:
view plaincopy to clipboardprint?
#region 广告下文字链
public static string getTopAdList(params object[] args)
{
BeanOper oper = new BeanOper();
StringBuilder result = new StringBuilder();
result.Append("<div class=\"ad1\">");
result.Append("<ul>");
result.Append(oper.getAdNewsHtml(3519, 1, 9, "ad1_"));
result.Append("</ul>");
result.Append("<div class=\"clear\"></div>");
result.Append("</div>");
return result.ToString();
}
#endregion
CacheSvr.saveCache("TopAdList", new CacheSvr.ProcessDataDelegate(IndexHtml.getTopAdList), new object[] { "" })
- 上一篇:学习使用.NET多线程传参数方式
- 下一篇:ASP.NET中Web应用程序认证例子