【问题标题】:Access appSettings in web.config from Thread in Class Library project从类库项目中的线程访问 web.config 中的 appSettings
【发布时间】: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


    【解决方案1】:

    TempXmlFolder 传递到线程中。不要依赖HttpContext.Current。或者,将HttpContext.Current 的值传递给线程,稍后再计算TempXmlFolder 的值。

    您可以使用任何您想要的方式传递值。可能是您使用 lambda 捕获的字段或局部变量。

    【讨论】:

    • 目前我正在将 Current HttpContext 传递给 Thread 方法。但是thread safety 将当前的HttpContext 传递给另一个Thread 会有什么问题吗?
    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 2017-04-19
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多