简体   繁体   English

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

[英]How to synchronize writing to file in ASP.Net global.asax?

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. 只要ASP.Net应用程序中发生未处理的异常,就会运行此代码。 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();
        }
    }
}

1 - you can use the singleton pattern and create a class that will handle this file creation/append or 1-您可以使用单例模式并创建一个类来处理此文件的创建/添加或

2 - use "lock" 2-使用“锁定”

3 - as suggested, use elmah 3-按照建议使用elmah

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM