使用线程访问的类库使用httpcontext.current

在类库中使用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;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值