多線程中使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM