Test on Application_End and Application_Start event triggering conditions (to be continued)

Source: Internet
Author: User

Test Project Setup

Define a simple MVC project that has the following files:

(1)

public class Startup{    public void Configuration(IAppBuilder app)    {        app.Run(context =>        {            return Task.Run(                async () => {                    await Task.Delay(600);                    await context.Response.WriteAsync("Hello, world." + context.Request.Uri);                });        });    }}

(2)

public class Global : System.Web.HttpApplication{    protected void Application_Start(object sender, EventArgs e)    {        DebugUtils.Log("Application_Start");        Task.Run(() => { DebugUtils.beginLog($"bugLog.txt"); });        for (long i = 0; i < 10000000000; i++) ;        DebugUtils.Log("Application_Start finished");    }    protected void Application_End(object sender, EventArgs e)    {        DebugUtils.Log("Application_End");        for (long i = 0; i < 10000000000; i++) ;        DebugUtils.Log("Application_End finished");    }}

(3)

public class DebugUtils{    public static ConcurrentQueue<string> queue = new ConcurrentQueue<string>();    public static void beginLog(string fileName)    {        string dirPath = "G:\\c#\\www\\debugLog\\";        if (!Directory.Exists(dirPath))            Directory.CreateDirectory(dirPath);        using (FileStream fs = new FileStream(dirPath + "/" + fileName, FileMode.Append))        {            using (StreamWriter sw = new StreamWriter(fs))            {                string str;                while (true)                {                    if (queue.TryDequeue(out str))                    {                        sw.WriteLine(str);                        sw.Flush();                    }                }            }        }    }    public static void Log(string str)    {        queue.Enqueue("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "]--[" + Thread.CurrentThread.ManagedThreadId + "]--" + str);    }}
Test general Operations

After the site is deployed to IIS, modify config, bin folder, site shutdown, restart, recycle thread pool operation, log has application_end trigger log. Subsequent visits to the page will also have Application_Start log records.

High concurrency

Use the tool to simulate requests for high concurrency access to this site

In the meantime, modify config, log file only Application_End records, but no Application_Start records.
Modify config again, this time only Application_Start records, but there is no end of the. Try it many times and it always turns out this way.

Although the records in the above log appear to be commonplace, this is not the case.

The following changes were made (new log files are used for each boot)

Also made several changes to the config file, the new log records are as follows

You can see that the Application_Start event does not wait for the application_end to finish executing before triggering.

Questions to be resolved:
    1. The situation in the above test
      When using the same log file earlier, the log only records the part because the file is occupied, so why is there no exception.
      What happens when there is a regular alternation ...

    2. Problems encountered in the project

The Log4net log is used in the project and the configuration file is as follows:

<?xml version="1.0" encoding="utf-8" ?><log4net><appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >    <file value="App_Data/Logs/Logs.txt" />    <encoding value="utf-8" />    <appendToFile value="true" />    <rollingStyle value="Size" />    <maxSizeRollBackups value="10" />    <maximumFileSize value="10000KB" />    <staticLogFileName value="true" />    <layout type="log4net.Layout.PatternLayout">    <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />    </layout></appender><root>    <appender-ref ref="RollingFileAppender" />    <level value="DEBUG" /></root></log4net>

Application_Start:

    protected override void Application_Start(object sender, EventArgs e)    {        Clock.Provider = ClockProviders.Utc;        //Log4Net configuration        AbpBootstrapper.IocManager.IocContainer            .AddFacility<LoggingFacility>(f => f.UseAbpLog4Net()                .WithConfig(Server.MapPath("log4net.config"))            );        base.Application_Start(sender, e);        SingletonDependency<IOnlineUserManager>.Instance.ReloadWhenApplicationStart();    }

After the site is published, often after a application_end event is triggered, the log is no longer logged, and after a period of time, there will be a new log appears (Application_Start log is the beginning).

If the Application_End event is triggered, then the Application_Start will be triggered, that singletondependency . Instance.reloadwhenapplicationstart (); Why does this line of code often not take effect?

Whether as in the above test, there is a problem of execution order, first triggered the Application_Start, and then triggered application_end, resulting in reading the cache session information, the corresponding file has not been saved.

To modify a log record file
public class debugutils{public static Debugutils Instance = new Debugutils ();    public static concurrentqueue<string> queue = new concurrentqueue<string> ();        public void Beginlog (string fileName) {string dirpath = "g:\\c#\\www\\debuglog\\"; if (!        Directory.Exists (Dirpath)) directory.createdirectory (Dirpath); using (FileStream fs = new FileStream (Dirpath + "/" + FileName, Filemode.append)) {using (StreamWriter                SW = new StreamWriter (fs)) {string str; while (true) {if (queue. Trydequeue (out str)) {SW.                        WriteLine (str); Sw.                    Flush (); }}}}} public void Log (String str, string date) {queue. Enqueue ($ "[{date}]--[{thread.currentthread.managedthreadid}]-[{this.    GetHashCode ()}]-{str} "); }}public class Global:sYstem. web.httpapplication{protected void Application_Start (object sender, EventArgs e) {DebugUtils.Instance.Log ("        Application_Start ", DateTime.Now.ToString (" Yyyy-mm-dd HH:mm:ss FFF "));        Task.run (() = {DebugUtils.Instance.beginLog ($ "buglog{datetime.now.tostring (" yyyymmdd-hhmmssfff ")}.txt");});        for (long i = 0; i < 10000000000; i++);    DebugUtils.Instance.Log ("Application_Start finished", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss fff"); } protected void Application_End (object sender, EventArgs e) {DebugUtils.Instance.Log ("Application_End", Dat        ETime.Now.ToString ("Yyyy-mm-dd HH:mm:ss FFF"));        for (long i = 0; i < 10000000000; i++);    DebugUtils.Instance.Log ("Application_End finished", DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss fff"); }}

Test for Application_End and Application_Start event triggering (to be continued)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.