某天,小菜在写一个异步程序的时候,突然提出这样的一个问题,以前写cache是在page类或者当前上下文的,
那我在异步岂不是要把当前上下文传进去才能读取cache的值吗?如果异步里面方法多的话,岂不是每一个方法都要设一个HttpContext的参数?
于是,他就有了下面的这段程序的写法
protected
void
Page_Load(
object
sender, EventArgs e)
{
{
.....
System.Threading.ThreadPool.QueueUserWorkItem(AsyncHandler, HttpContext.Current,list);
......
}
protected void AsyncHandler( object _obj)
{
System.Threading.ThreadPool.QueueUserWorkItem(AsyncHandler, HttpContext.Current,list);
......
}
protected void AsyncHandler( object _obj)
{
object[] obj =_obj as object[];
HttpContext context = obj[0] as HttpContext;
object userObj = context.Cache[ " userObj " ] ;
......
}
HttpContext context = obj[0] as HttpContext;
object userObj = context.Cache[ " userObj " ] ;
......
}
当然, 小菜当然是提这问题的时候没有经过思考的,还没想起cache是存在于app block里面的,kakim提示他用强大的Reflector查看一下,HttpContext.Cache里面做了点什么事?
小菜同学马上明白了,于是找到了下面的一段
public
Cache Cache
{
get
{
return HttpRuntime.Cache;
}
}
{
get
{
return HttpRuntime.Cache;
}
}
好了,一切真相大白,现在问题解决了,可以省掉HttpContext拆箱的过程了,直接用HttpRuntime.Cache对象就可以访问缓存时面的数据
所以上面的异步方法就可以改成下面的
protected
void
AsyncHandler(
object
obj)
{
......
object userObj = HttpRuntime.Cache[ " userObj " ] ;
......
}
{
......
object userObj = HttpRuntime.Cache[ " userObj " ] ;
......
}