Profile Memory Usage of Session State ASP.Net

2020-02-23 04:37发布

问题:

I'm trying to figure out the size of a particular session state. On one of our heavy pages (lots of data in a table) it gets progressively slower. The issue is resolved by logging out of the system.

I've profiled the page looking for JavaScript memory leaks, but I didn't find anything. My next plan of attack is too look at ViewState and Session State. ViewState will be simple, but Session State poses a challenge.

Does anyone know of any tricks or tools that would help figure out the size of Session State?

EDIT

The session state is InProc.

回答1:

Measure it:

int totalBytes;
var formatter = new BinaryFormatter();
for(int i = 0; i < Session.Count; i++)
{
    using (var stream = new MemoryStream())
    {
        formatter.Serialize(stream, Session[i]);
        stream.Flush();
        totalBytes += stream.Length;
    }
}

Also I believe that if you enable tracing it will show you some details about the session (not sure about this, never tried it myself).



回答2:

Some have mentioned ASP.NET tracing but I didn't have much luck with it myself. I could view trace information but the session section was never populated.

However, here's a useful article from CodeProject that uses http handlers to view the current session (and cache).

There are two issues with respect to this question:

  1. It won't present storage space when session state is InProc

    When Session State is running InProc (In Process) the actual objects that form the content are not stored in the collection, only reference to the objects. The figures for the size taken up by these objects "in" session state would be misleading under these circumstances.

  2. It uses BinaryFormatter which "gives only a very rough approximation" of the size of the session data. It's only an approximation as ASP.NET "uses an optimized internal formatter for basic types such as int, string, bool, etc"

That said, I've found it useful and I thought it was worth sharing. It may be worth pushing the session state out of process for profiling size.