Web Request Execution Time – C# example
In this article, you find a simple example of how to create a custom message handler for a Web request execution time logging.
Sometimes, to optimize the performance, you may need to find out the Web request execution time. For example, you want to know how much time is taken to read a file in the file system or download data from a remote server.
Message Handler for Logging the Time of File Loading
Creating a TimeLoggerMessageHandler for a Web Request Execution Time Logging
The following code snippet shows how to create a TimeLoggerMessageHandler to log the time taken for reading a file from the file system.
1// Log request time with custom C# message handler
2
3// Define the TimeLoggerMessageHandler class that is derived from the MessageHandler class
4public class TimeLoggerMessageHandler : MessageHandler
5{
6 // Override the Invoke() method
7 public override void Invoke(INetworkOperationContext context)
8 {
9 // Start the stopwatch
10 Stopwatch stopwatch = Stopwatch.StartNew();
11
12 // Invoke the next message handler in the chain
13 Next(context);
14
15 // Stop the stopwatch
16 stopwatch.Stop();
17
18 // Print the result
19 Debug.WriteLine("Request: " + context.Request.RequestUri);
20 Debug.WriteLine("Time: " + stopwatch.ElapsedMilliseconds + "ms");
21 }
22}
Use the Stopwatch class in the System.Diagnostics Namespace to accurately measure the time it takes to execute the Web request. The StartNew() method starts to log time for completing the Web request until the Stop() method is called.
Adding the TimeLoggerMessageHandler to the Pipeline
The Configuration() constructor initializes an instance of the Configuration class. After the configuration is created, the GetService <INetworkService>() and MessageHandlers.Insert() methods are invoked. The Insert() method adds the TimeLoggerMessageHandler at the first place in the collection of message handlers.
Use the
HTMLDocument(address, configuration
) constructor to initialize an HTML Document and implement the example for logging the document’s loading time.
1// Track HTML load time in C# using a custom network message handler
2
3// Create an instance of the Configuration class
4using Configuration configuration = new Configuration();
5
6// Add the TimeLoggerMessageHandler to the chain of existing message handlers
7INetworkService service = configuration.GetService<INetworkService>();
8MessageHandlerCollection handlers = service.MessageHandlers;
9
10handlers.Insert(0, new TimeLoggerMessageHandler());
11
12// Prepare path to a source document file
13string documentPath = Path.Combine(DataDir, "input.htm");
14
15// Initialize an HTML document with specified configuration
16using HTMLDocument document = new HTMLDocument(documentPath, configuration);
You can download the complete examples and data files from GitHub.