在线程中无法Mappath,主要是因为:HttpContext.Current为null,所以:
关键在于构造一个HttpContext
{
private static HttpContext ct = new HttpContext(new HttpRequest("", "http://dewrqiwe5555rqwekxczvm23482734zxcadfasdf.com", ""), new HttpResponse(new System.IO.StringWriter()));
//...省略若干
{
return ct.Server.MapPath(strPath);
}
}
测试:
{
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/>");
}
}
{
get
{
return _sb.ToString() + "<br>BusyThread Count:" + _nTmpBusyThread.ToString() + "<br>WorkTimes:" + _ulWorkTimes.ToString();
}
}
}
aspx页面省略,大意: