现在的位置: 首页 > 综合 > 正文

原:解决ASP.NET在线程中无法Mappath的问题

2012年10月27日 ⁄ 综合 ⁄ 共 2083字 ⁄ 字号 评论关闭

在线程中无法Mappath,主要是因为:HttpContext.Current为null,所以:

关键在于构造一个HttpContext

public class CSiteConfig
    {
        private static HttpContext ct = new HttpContext(new HttpRequest("", "http://dewrqiwe5555rqwekxczvm23482734zxcadfasdf.com", ""), new HttpResponse(new System.IO.StringWriter()));

  //...省略若干

  public static string MapPath(string strPath)
        {
            return ct.Server.MapPath(strPath);
        }

   }

 

测试:

public class ProcessThread
    {      

        protected ProcessThread()
        {
            _sb.AppendLine(DateTime.Now.ToString("HH:mm:ss.fff")+"SqlProcessThread Start.<br/>");
            _sb.AppendLine("MapPath:Server.MapPath(/news)  " + HttpContext.Current.Server.MapPath ("/news") + "<br/>");

            int nThreadCount = 0;
            for (nThreadCount = 1; nThreadCount < nMaxThread + 1; nThreadCount++)
            {
                Thread t = new Thread(new ThreadStart(SqlWorkThread));
                t.Name = "SQLThread NO." + nThreadCount.ToString();
                t.Start();
            }
            _sb.AppendLine(DateTime.Now.ToString("HH:mm:ss.fff") + "  .OK.<br/>");
        }
        public static ProcessThread Instance()
        {
            if (_this == null)
                _this = new ProcessThread();
            return _this;
        }
       
        public void SqlWorkThread()
        {//线程中
            _sb.AppendLine(Thread.CurrentThread.Name + " Starting...<br>");
            try{
            _sb.AppendLine(Thread.CurrentThread.Name+" MapPath:CSiteConfig.Instance().MapPath(/news)  " + CSiteConfig.MapPath("/html") + "<br/>");//此处如果用:HttpContext.Current.Server.Mappath保证出错!
            }
            catch (Exception ex)
            {
                _sb.AppendLine(ex.Message+"<br/>");
                _sb.AppendLine(ex.Source + "<br/>");
                _sb.AppendLine(ex.TargetSite + "<br/>");
            }

  }

public string GetLog
        {
            get
            {
                return _sb.ToString() + "<br>BusyThread Count:" + _nTmpBusyThread.ToString() + "<br>WorkTimes:" + _ulWorkTimes.ToString();
            }
        }

    }

 

 aspx页面省略,大意:

Label1.Text = " MapPath:CSiteConfig.MapPath(/html)  " + LeesCMS.Common.CSiteConfig.MapPath("/html") + "<br/>"+LeesCMS.Common.ProcessThread.Instance().GetLog;

 

 

抱歉!评论已关闭.