簡體   English   中英

從類庫項目中的線程訪問web.config中的appSettings

[英]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();

但是由於ThreadHttpContext.Current為null,因此我無法訪問當前的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");
      //...

TempXmlFolder傳遞到線程中。 不要依賴HttpContext.Current 或者,將HttpContext.Current的值傳遞給線程,然后再計算TempXmlFolder的值。

您可以使用任意方式傳遞值。 可能是您使用lambda捕獲的字段或局部變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM