如何在ASP.Net global.asax中同步写入文件?

时间:2012-10-26 03:23:43

标签: c# asp.net file-io

我正在写一个文件,该文件是为一年中的每个日期创建的,通过以下代码编写。只要在ASP.Net应用程序中发生未处理的异常,此代码就会运行。我的问题是当许多用户使用该网站时,由于同时发生多个错误,可能导致此代码被点击,这可能导致多个请求创建或写入同一文件。什么是在这种情况下的解决方案,所以只有一个请求执行与写入文件相关的代码?

   private void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs
    string errorGuid    = Guid.NewGuid().ToString("D");
    if (HttpContext.Current.Server.GetLastError() != null)
    {
        Exception err = HttpContext.Current.Server.GetLastError();
        string header = String.Format("/*****\t\t{0}:{1}\t\t*****/", "Start", errorGuid);
        string footer = String.Format("/*****\t\t{0}:{1}\t\t*****/", "End", errorGuid);
        string errorText = String.Format("{0}{5}Exception DateTime: {1}{5}Reference #: {2}{5}Exception:{5}=========={5}{3}{5}{4}{5}", header, System.DateTime.Now, errorGuid, err.ToString(), footer, Environment.NewLine);

        // '~/ErrorReports/Logs/ErrorLog.log' must exist, else we will get an error 

        using (System.IO.TextWriter write = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/ErrorReports/Logs/ErrorLog_" + DateTime.Now.ToShortDateString() + ".log"), true, System.Text.Encoding.UTF8))
        {
            write.WriteLine(errorText);
            write.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

1 - 您可以使用单例模式并创建一个将处理此文件创建/附加的类或

2 - 使用“锁定”

3 - 如建议的那样,使用elmah