在类库中使用httpcontext.current很简单,添加System.web引用就可以。前两天做一计划任务,使用了Thread.在使用线程调用另一个类库的方法时,发现httpcontext.current一直为null。苦思不得其解。后来网上查找问题,才突然明白,启用一个新的线程,已经不是page请求,当然没有httpcontext.current啦。
想明白了这点,开始思考解决的办法-----给线程传参。
才发现线程调用不能直接传参数,后来在网上找到了这个方法:
//执行多个任务
foreach (IScheduledTask task in Tasks)
{
System.Threading.Thread t = SimpleThread.CreateThread(new SimpleThread.Start(task.Execute), hc);//hc为要传的参数
t.Start();
t.Join(System.Threading.Timeout.Infinite);
}
public class SimpleThread
{
public delegate void Start(object o);
private class Args
{
public object o;
public Start s;
public void work()
{
s(o);
}
}
public static System.Threading.Thread CreateThread(Start s, Object arg)
{
Args a = new Args();
a.o = arg;
a.s = s;
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(a.work));
return t;
}
}