0

我可以appSettings从另一个引用的类库项目中的方法访问我的 ASP.NET web.config 文件中的部分,当它被称为新的时Thread?我正在通过属性访问设置

 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();

但由于HttpContext.Current内部为 null Thread,我无法访问当前的 Web 服务器配置文件。

除了将电流传递HttpContextThread如果不是,我需要注意哪些事情来保持线程安全?

编辑#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");
      //...
4

1 回答 1

1

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

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

于 2013-08-20T15:35:27.747 回答