4

I'd like to write some automated tests to measure how much database IO is occurring during particular processes in our application and ensure they never go above a certain threshold.

Outside of EF, you would:

  1. Open SQL Server Management Studio
  2. set io statistics on
  3. ...run your queries
  4. ... look at the response returned in the Messages window see the statistics.

So I'm wondering if there is some way to get these same measurements as part of the call to DbContext.SaveChanges. I think you could override the SaveChangesAsync and SaveChanges methods to execute the "set io statistics" statement, but doing it that way would result in an extra database hit and also I wouldn't know how to get the statistics back after SaveChangesAsync was complete.

Any thoughts or ideas?

1 Answer 1

3

The statistics messges come back as Info Messages, which you can aggregate. Eg in EF Core, something like:

            db.Database.OpenConnection();
            var con = db.Database.GetDbConnection() as SqlConnection;
            db.Database.ExecuteSqlCommand("set statistics io on");
            con.InfoMessage += (s, a) =>
            {
                if (a.Errors[0].Number == 3615)
                {
                    Console.WriteLine(a.Message);
                }
            };

A better approach is probably to monitor on the server. You can use an XEvents session to capture the logout event, which carries summary statistics for each session that ends ( or is reused from the connection pool). EG

CREATE EVENT SESSION [Session Stats] ON SERVER 
ADD EVENT sqlserver.logout(
    ACTION(sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.database_id,sqlserver.database_name,sqlserver.nt_username,sqlserver.server_principal_name,sqlserver.session_id,sqlserver.username))
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
GO
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.