[英]Access appSettings in web.config from Thread in Class Library project
将另一个新类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
为null,因此我无法访问当前的Web服务器配置文件。
除了将当前的HttpContext
传递给Thread
您是否可以建议其他方法? 如果没有,为保证线程安全我必须注意些什么?
目前,我正在将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");
//...
将TempXmlFolder
传递到线程中。 不要依赖HttpContext.Current
。 或者,将HttpContext.Current
的值传递给线程,然后再计算TempXmlFolder
的值。
您可以使用任意方式传递值。 可能是您使用lambda捕获的字段或局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.