Why does Session_Start in Global.asax.cs cause per

2019-03-19 17:59发布

When I create an empty Session_Start handler in Global.asax.cs it causes a significant hit when rendering pages to the browser.

How to reproduce:

Create an empty ASP.NET MVC 3 web application (I am using MVC 3 RC2). Then add a Home controller with this code:

public class HomeController : Controller
{
  public ActionResult Index()
  {
    return View();
  }
  public ActionResult Number(int id)
  {
    return Content(id.ToString());
  }
}

Next create a view Home/Index.cshtml and place the following in the BODY section:

@for (int n = 0; n < 20; n++)
{ 
  <iframe src="@Url.Content("~/Home/Number/" + n)" width=100 height=100 />
}

When you run this page, you'll see 20 IFRAMEs appear on the page, each with a number inside it. All I'm doing here is creating a page that loads 20 more pages behind the scenes. Before continuing, take note of how quickly those 20 pages load (refresh the page a few times to repeat the loads).

Next go to your Global.asax.cs and add this method (yes, the method body is empty):

protected void Session_Start()
{
}

Now run the page again. This time you'll notice that the 20 IFRAMEs load much slower, one after the other about 1 second apart. This is strange because we're not actually doing anything in Session_Start ... it's just an empty method. But this seems to be enough to cause the slowdown in all subsequent pages.

Does anybody know why this is happening, and better yet does anybody have a fix/workaround?

Update

I've discovered that this behavior only occurs when the debugger is attached (running with F5). If you run it without the debugger attached (Ctrl-F5) then it seems to be ok. So, maybe it's not a significant problem but it's still strange.

2条回答
霸刀☆藐视天下
2楼-- · 2019-03-19 18:48

tl;dr: If you face this problem with Webforms and don't require write access to session state in that particular page, adding EnableSessionState="ReadOnly" to your @Page directive helps.


Apparently, the existance of Session_Start alone forces ASP.NET to execute all requests originating from the same Session sequentially. This, however, can be fixed on a page-by-page basis if you don't need write access to the session (see below).

I've created my own test setting with Webforms, which uses an aspx page to deliver images.1

Here's the test page (plain HTML, start page of the project):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title></title></head>
<body>
    <div>
        <img src="GetImage.aspx?text=A" />
        <img src="GetImage.aspx?text=B" />
        <img src="GetImage.aspx?text=C" />
        <img src="GetImage.aspx?text=D" />
        <img src="GetImage.aspx?text=E" />
        <img src="GetImage.aspx?text=F" />
        <img src="GetImage.aspx?text=G" />
        <img src="GetImage.aspx?text=H" />
        <img src="GetImage.aspx?text=I" />
        <img src="GetImage.aspx?text=J" />
        <img src="GetImage.aspx?text=K" />
        <img src="GetImage.aspx?text=L" />
    </div>
</body>
</html>

Here's the aspx page (GetImage.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetImage.aspx.cs" Inherits="CsWebApplication1.GetImage" %>

And the relevant parts of the codebehind (GetImage.aspx.cs, using and namespace skipped):

public partial class GetImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Debug.WriteLine("Start: " + DateTime.Now.Millisecond);
        Response.Clear();
        Response.ContentType = "image/jpeg";

        var image = GetDummyImage(Request.QueryString["text"]);
        Response.OutputStream.Write(image, 0, image.Length);
        Debug.WriteLine("End: " + DateTime.Now.Millisecond);
    }

    // Empty 50x50 JPG with text written in the center
    private byte[] GetDummyImage(string text)
    {
        using (var bmp = new Bitmap(50, 50))
        using (var gr = Graphics.FromImage(bmp))
        {
            gr.Clear(Color.White);
            gr.DrawString(text,
                new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular, GraphicsUnit.Point),
                Brushes.Black, new RectangleF(0, 0, 50, 50),
                new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
            using (var stream = new MemoryStream())
            {
                bmp.Save(stream, ImageFormat.Jpeg);
                return stream.ToArray();
            }
        }
    }
}

Test runs

  • Run 1, unmodified: The page loads fast, the output window shows a random mix of Start and Ends, which means that the requests get processed in parallel.

  • Run 2, add empty Session_Start to global.asax (need to hit F5 once in the browser, don't know why this is): Start and End alternate, showing that the requests get processed sequentually. Refreshing the browser multiple times shows that this has performance issues even when the debugger is not attached.

  • Run 3, like Run 2, but add EnableSessionState="ReadOnly" to the @Page directive of GetImage.aspx: The debug output shows multiple Starts before the first End. We are parallel again, and we have good performance.


1 Yes, I know that this should be done with an ashx handler instead. It's just an example.

查看更多
Explosion°爆炸
3楼-- · 2019-03-19 18:53

Can't tell you what your debugger is doing (intellitrace? detailed logging? first-chance exceptions?), but you're still in the hands of the sessions ability to handle concurrent requests.

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

Source: ASP.NET Session State Overview, my emphasis

查看更多
登录 后发表回答