3382627c8c33b3df4a611ee796ba4bd2866b6529
CoreProfiler
NUGET INSTALL coreprofiler -Version 1.1.4
用於紀錄特定區塊內的執行耗時。
基本手法如下:
var stepName = $"{class_name}.{method_name}";
using (ProfilingSession.Current.Step(stepName))
{
// 需要計時的程式碼片段
}
由於大部分都是使用相同的紀錄模型,因次本範例內提供一個擴充方法,透過反射取得類別與方法名稱。
// ./CoreProfilerExample.Common/Extensions/MethodBaseExtension.cs
public static IDisposable ProfilingStep(this MethodBase method, string? stepName = null)
{
if (stepName == null)
{
// 取得方法的類型物件
var methodType = method.ReflectedType;
// 取得類別的類型物件
var classType = methodType?.ReflectedType ?? methodType;
// 取出類別底下所有非同步類型的方法,比對出當前的方法類型
var classMethodType = classType?
.GetMethods()
.Select(x => new
{
Method = x,
Attribute = x.GetCustomAttribute<AsyncStateMachineAttribute>(),
})
.FirstOrDefault(x => x.Attribute?.StateMachineType == methodType);
var className = classType?.Name ?? "無法取得類別名稱";
var methodName = classMethodType?.Method.Name ?? method.Name ?? "無法取得方法名稱";
stepName = $"{classType?.Name}.{methodName}";
}
return ProfilingSession.Current.Step(stepName);
}
擴充 MethodBase 類別,開發者可以自行決定是否要輸入stepName參數,若沒有輸入則會透過反射的技術取得類別與方法的名稱,作為紀錄耗時的區塊階段名稱。
反射的說明: 透過MethodBase來取得方法的Type物件,再取得類別的Type物件,原本這樣就可以使用Name來取得類別與方法的名稱,但方法若為非同步,則會取出不好閱讀的名稱,因次需要再執行以下操作來取得易於閱讀的名稱:
var classMethodType = classType?
.GetMethods()
.Select(x => new
{
Method = x,
Attribute = x.GetCustomAttribute<AsyncStateMachineAttribute>(),
})
.Where(x => x.Attribute?.StateMachineType == methodType)
.FirstOrDefault();
利用類別的Type取得其底下的所有方法,再透過比對方法Type的方式取得方法的MethodInfo,就可以使用Name來取得易讀的方法名稱了。
擴充方法的基本使用方法如下:
using (MethodBase.GetCurrentMethod()?.ProfilingStep())
{
// 需要計時的程式碼片段
}
using (MethodBase.GetCurrentMethod()?.ProfilingStep("階段名稱"))
{
// 需要計時的程式碼片段
}
CoreProfiler.Web
NUGET INSTALL CoreProfiler.Web -Version 1.1.4
將每個階段要追蹤的程式碼包裝好後,再來安裝方便查找紀錄的介面,如下:
// ./CoreProfilerExample/Infrastructure/Extensions/DependencyInjectionExtension.cs
public static IApplicationBuilder UseCoreProfiler(this IApplicationBuilder app)
{
CoreProfilerOption.UseCoreProfilerSetting();
app.UseCoreProfiler(true);
return app;
}
使用CoreProfilerOption.UseCoreProfilerSetting()方法來產生GUI所需的相關設定參數後,使用app.UseCoreProfiler(true)注入應用程式,其參數true表示每一個紀錄片段是否要往下查找是否有其他的紀錄片段。
啟動後連結 /nanoprofiler/view 確認是否有啟用成功。
執行紀錄如下:
紀錄的詳細如下:
Description
Languages
C#
100%