1

I am writing to a file, that is created for each date of the year, through code below. This code runs whenever, an unhandled exception occurs in an ASP.Net app. My problem is when many users are using the website, then this code could be hit due to several errors occurring at the same time, which could result in multiple requests to create or write to same file. What is the solution in this case so only one request executes the code related to writing to a file?

   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();
        }
    }
}
Sunil
  • 20,653
  • 28
  • 112
  • 197

1 Answers1

1

1 - you can use the singleton pattern and create a class that will handle this file creation/append or

2 - use "lock"

3 - as suggested, use elmah

Retired_User
  • 1,595
  • 11
  • 17
  • Gmoliv - Thanks. Can you provide sample code for using lock in global.asax? – Sunil Oct 26 '12 at 04:12
  • Sunil, take a look at this question http://stackoverflow.com/questions/6029804/how-does-lock-work-exactly-c-sharp – Retired_User Oct 26 '12 at 11:33
  • SLaks, why #1 won't help? Seems to me that a single class writing to the file would prevent concurrency (check if file exists in the constructor, if not creates it and provide method to append data). I'm failing to see the problem here, can you help? Thanks – Retired_User Oct 26 '12 at 11:37
  • @Gmoliv: You can still end up writing two things at once. – SLaks Oct 26 '12 at 12:21