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// Define the TimeLoggerMessageHandler class that is derived from the MessageHandler class
2public class TimeLoggerMessageHandler : MessageHandler
3{
4 // Override the Invoke() method
5 public override void Invoke(INetworkOperationContext context)
6 {
7 // Start the stopwatch
8 var stopwatch = Stopwatch.StartNew();
9
10 // Invoke the next message handler in the chain
11 Next(context);
12
13 // Stop the stopwatch
14 stopwatch.Stop();
15
16 // Print the result
17 Debug.WriteLine("Request: " + context.Request.RequestUri);
18 Debug.WriteLine("Time: " + stopwatch.ElapsedMilliseconds + "ms");
19 }
20}
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// Create an instance of the Configuration class
2using var configuration = new Configuration();
3
4// Add the TimeLoggerMessageHandler to the chain of existing message handlers
5var service = configuration.GetService<INetworkService>();
6var handlers = service.MessageHandlers;
7
8handlers.Insert(0, new TimeLoggerMessageHandler());
9
10// Prepare path to a source document file
11string documentPath = Path.Combine(DataDir, "input.htm");
12
13// Initialize an HTML document with specified configuration
14using var document = new HTMLDocument(documentPath, configuration);
You can download the complete examples and data files from GitHub.