【发布时间】:2013-08-20 14:51:47
【问题描述】:
当另一个引用的类库项目中的方法被称为新的Thread 时,我能否访问我的 ASP.NET web.config 文件中的appSettings 部分?
我正在通过属性访问设置
private static string TempXmlFolder
{
get
{
return System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ReceiptTempPath"] ?? "~/Receipts/TempXML");
}
}
该事项有生成收据的扩展方法。
internal static void GenerateReceipt(this IMatter matter)
{
try
{
string XmlFile = TempXmlFolder + "/Rec_" + matter.MatterID + ".xml";
// ...
// Generating receipt from the matter contents
// ...
// Saving generated receipt
}
catch (Exception ex)
{
ex.WriteLog();
}
}
我将收据生成作为类库中的新线程调用,例如
Thread printThread = new Thread(new ThreadStart(this.GenerateReceipt));
// To avoid exception 'The calling thread must be STA, because many UI components require this' (Using WPF controls in receipt generation function)
printThread.SetApartmentState(ApartmentState.STA);
printThread.Start();
// ...
// Do another stuffs
// ...
// Wait to generate receipt to complete
printThread.Join();
但由于Thread 中的HttpContext.Current 为空,我无法访问当前的Web 服务器配置文件。
除了将当前的HttpContext 传递给Thread 之外,您能否提出任何建议?如果不是,我需要注意哪些事项来保证线程安全?
编辑#1
目前我正在将 HttpContext 传递给线程,例如
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
Thread printThread = new Thread(() => this.GenerateReceipt(currentContext));
在函数中,
internal static void GenerateReceipt(this IMatter matter, System.Web.HttpContext htCont)
{
string TempXmlFolder = htCont.Server.MapPath(ConfigurationManager.AppSettings["ReceiptTempPath"] ?? "~/Receipts/TempXML");
//...
【问题讨论】:
标签: asp.net multithreading c#-4.0 thread-safety httpcontext