代码之家  ›  专栏  ›  技术社区  ›  Sen Jacob

从类库项目中的线程访问web.config中的appSettings

  •  0
  • Sen Jacob  · 技术社区  · 13 年前

    我可以访问吗 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 线 ,我无法访问当前的web服务器配置文件。

    除了通过电流,你能建议其他方法吗 HttpContext 线 ? 如果没有,我必须注意哪些事情才能保证线程安全?

    编辑#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");
          //...
    
    1 回复  |  直到 13 年前
        1
  •  1
  •   usr    13 年前

    通过 TempXmlFolder 插入螺纹。不要依赖 HttpContext.Current 。或者,传递的值 HttpContext.Current(当前HTTP上下文) 到线程并计算的值 TempXml文件夹 后来

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

    推荐文章