zoukankan      html  css  js  c++  java
  • 多线程中使用HttpContext.Current为null的解决办法

     HttpContext.Current.Server.MapPath(logFile)   这个是得到具体路径的方法  正常情况下是可以的 多线程情况下就为null

    下边的代码原本的作用是把网站的异常错误信息写入log.txt中 

     这里抽出部分代码是我测试System.Timers.Timer的  

    把网站的异常错误信息写入log.txt的原代码在这里:http://www.cnblogs.com/0banana0/archive/2012/05/04/2483246.html

    public static void LogException(Exception exc, string source)
    {
    
    
    string logFile = "App_Data/ErrorLog.txt";
    
            //多线程的话HttpContext.Current这个会为null就执行else里边的东东
            if (HttpContext.Current != null)
            {
                logFile = HttpContext.Current.Server.MapPath(logFile);
            }
            else
            {
                //多线程执行这里
                logFile = logFile.Replace("/", "\\");
                if (logFile.StartsWith("\\"))//确定 String 实例的开头是否与指定的字符串匹配。为下边的合并字符串做准备
                {
                    logFile = logFile.TrimStart('\\');//从此实例的开始位置移除数组中指定的一组字符的所有匹配项。为下边的合并字符串做准备
                }
           //AppDomain表示应用程序域,它是一个应用程序在其中执行的独立环境       
           //AppDomain.CurrentDomain 获取当前 Thread 的当前应用程序域。
           //BaseDirectory 获取基目录,它由程序集冲突解决程序用来探测程序集。
            //AppDomain.CurrentDomain.BaseDirectory综合起来就是返回此代码所在的路径
            //System.IO.Path.Combine合并两个路径字符串
           //Path.Combine(@"C:\11","aa.txt") 返回的字符串路径如后: C:\11\aa.txt
                logFile=System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logFile);
            }
    
            // Open the log file for append and write the log
            StreamWriter sw = new StreamWriter(logFile, true);
            sw.Write("******************** " + DateTime.Now);
            sw.WriteLine(" ********************");
     if (exc == null)
            {
                sw.Write(source);
            }
    
            sw.WriteLine();
            sw.Close();
    }

    Global.aspx里面的代码如下

    void Application_Start(object sender, EventArgs e) 
        {
            //在应用程序启动时运行的代码
           
            System.Timers.Timer t = new System.Timers.Timer(1000);
            t.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            t.AutoReset = true;
            t.Enabled = true;
        }
     private static void OnTimedEvent(object sender, EventArgs e)
        {
            ExceptionUtility.LogException(null, "Timer: Hello World");
        }

    网站启动后没隔一秒给log.txt中写入一次

    ******************** 2012/5/11 19:19:35 ********************
    Timer: Hello World

    这个只是简单的示例介绍timer的 以及遇到多线程HttpContext.Current为null的解决办法

    解决办法在这里找到的:http://topic.csdn.net/u/20090103/15/4e8b403e-5dfd-4afd-a364-1c38a18e5a03.html

  • 相关阅读:
    ubuntu下mysql的安装
    useradd和adduser的区别
    C和指针之学习笔记(6)
    C和指针之学习笔记(5)
    C和指针之学习笔记(4)
    Centos 7搭建Gitlab服务器超详细
    .NET Core sdk和runtime区别
    .NET平台历程介绍
    GitLabCICD
    Jenkins+gitlab+msbuild
  • 原文地址:https://www.cnblogs.com/0banana0/p/2496578.html
Copyright © 2011-2022 走看看