我正在开发一个.net核心项目。其中我必须计算我的await方法在执行时花费了多少时间。
[HttpPost]
public async Task<bool> InsertIntoDatabase([Frombody] StudentModel objStu) {
//For Each method and other stuff
await DoInsert(Fiels Details);
}
我在Ajax中调用这个方法。因此,在成功执行代码后,我想返回该方法所花费的时间(以分钟为单位)。
此插入过程包含 500 多条记录。所以,我有兴趣计算一下时间
一种方法是使用
Stopwatch
[HttpPost]
public async Task<bool> InsertIntoDatabase([Frombody] StudentModel student)
{
var clock = new Stopwatch();
clock.Start();
await DoInsert(student);
clock.Stop();
var minutes = clock.Elapsed.TotalMinutes();
}
为什么不在任务中返回包含时间和结果的自定义对象?
private async Task<MyClass> GetResult()
{}
public class MyClass
{
public bool Success { get; set; }
public long TimeInSeconds { get; set; }
}
我强烈建议您查看MiniProfiler。 设置非常简单!
<mini-profiler />
) 添加到您的 HTML 中(我也将其放入 Layout.cshtml 中)services.AddMiniProfiler(options =>
{
options.RouteBasePath = "/profiler";
options.SqlFormatter = new SqlServerFormatter();
});
app.UseStaticFiles()
:if (env.IsDevelopment())
{
app.UseMiniProfiler();
}
现在 MiniProfiler 已准备就绪,只会出现在开发中(第 5 步)。要分析一些代码,请执行以下操作:
using (MiniProfiler.Current.Step("This Will be the label displayed on the front end"))
{
//code you want to profile
}
现在运行您的代码,瞧! MiniProfiler 会在您的页面上放置一个非常小的表格(我认为它默认位于左上角)。每行都是请求的经过时间(也适用于 AJAX!)。
[HttpPost] { var stopwatch = Stopwatch.StartNew(); try { await DoInsert(objStu); stopwatch.Stop(); TimeSpan elapsedTime = stopwatch.Elapsed; double minutes = elapsedTime.TotalMinutes; return Ok(new { Success = true, ElapsedTimeInMinutes = minutes }); } catch (Exception ex) { return BadRequest(new { Success = false, ErrorMessage = ex.Message }); } }