.NET Core提供了两种方法来记录方法运行时间:
使用Stopwatch类
Stopwatch类是一个计时器,可以用来测量代码的运行时间。要使用Stopwatch类来记录方法运行时间,您可以按照以下步骤操作:
创建一个Stopwatch实例。
调用Start()方法开始计时。
在方法执行完毕后,调用Stop()方法停止计时。
调用Elapsed属性获取方法运行的时间。
以下是一个使用Stopwatch类记录方法运行时间的示例:
- using System;
- using System.Diagnostics;
-
- class Program
- {
- static void Main(string[] args)
- {
- // 创建一个Stopwatch实例
- Stopwatch sw = new Stopwatch();
-
- // 开始计时
- sw.Start();
-
- // 执行方法
- //...
-
- // 停止计时
- sw.Stop();
-
- // 获取方法运行时间
- TimeSpan elapsed = sw.Elapsed;
-
- // 输出方法运行时间
- Console.WriteLine("方法运行时间:{0}", elapsed);
- }
- }
-
输出:方法运行时间:00:00:00.0000000
使用中间件
.NET Core提供了一个名为IAsyncRequestTimeoutMiddleware的接口,可以用来记录方法运行时间。要使用IAsyncRequestTimeoutMiddleware来记录方法运行时间,您可以按照以下步骤操作:
在应用程序的Startup.cs文件中,将IAsyncRequestTimeoutMiddleware添加到Configure()方法的UseEndpoints()方法中。
在UseEndpoints()方法的参数中,设置RequestTimeout属性。
在方法中,使用HttpContext.Request.ExecutionTime属性获取方法运行时间。
以下是一个使用IAsyncRequestTimeoutMiddleware记录方法运行时间的示例:
- using System;
- using System.Net.Http;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Http;
-
- namespace Middleware
- {
- public class Startup
- {
- public void Configure(IApplicationBuilder app)
- {
- app.UseMiddleware<IAsyncRequestTimeoutMiddleware>();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapGet("/", async context =>
- {
- // 获取方法运行时间
- TimeSpan elapsed = context.Request.ExecutionTime;
-
- // 输出方法运行时间
- Console.WriteLine("方法运行时间:{0}", elapsed);
-
- // 返回响应
- return context.Response.WriteAsync("Hello, world!");
- });
- });
- }
- }
- }
-
输出:方法运行时间:00:00:00.0000000
具体使用哪种方法取决于您的具体需求。
如果您只需要记录单个方法的运行时间,那么可以使用Stopwatch类。
如果您需要记录多个方法或请求的运行时间,那么可以使用中间件。