我有一個POST控制器方法使用異步等待在很多服務和控制器級別我需要發送一些新的遺物參數。 New Relic在參數從非請求啓動的線程發送時發出警告日誌。如何在同一個線程上調用請求開始
NewRelic WARN: Agent API Error: An error occurred invoking API method "AddCustomParameter" - "System.InvalidOperationException: The API method called is only valid from within a transaction. This error can occur if you call the API method from a thread other than the one the transaction started on. at NewRelic.Agent.Core.Api.AsyncAgentApi.GetCurrentTransactionBuilder()
at NewRelic.Agent.Core.Api.AsyncAgentApi.AddCustomParameter(String key, String value)"
如何在我的控制器方法中調用將參數值發送到New Relic的代碼?
例如,下面的代碼在控制器中。
var threadid = Thread.CurrentThread.ManagedThreadId;
Log.Debug($"Before async method : {ThreadIdMessage(threadid)}");
var reportObject = await ReportService.GetReportAsync(requestModel).ConfigureAwait(true);
if (reportObject.PolicyModels != null)
{
threadid = Thread.CurrentThread.ManagedThreadId;
Log.Debug($"Before sending New Relic values: {ThreadIdMessage(threadid)}");
AddPoliciesCountInNewRelic(reportObject.PolicyModels.Count);
AddTotalTransactionsCountInNewRelic(
reportObject.PolicyModels.SelectMany(p => p.PolicyTransactionModels).Count());
threadid = Thread.CurrentThread.ManagedThreadId;
Log.Debug($"After sending New Relic values: {ThreadIdMessage(threadid)}");
}
將打印
DEBUG - Before async method : Current Thread Id: 5
DEBUG - Before sending New Relic values: Current Thread Id: 9
NewRelic.AddCustomParameter(CVPoliciesCount,2)
NewRelic.AddCustomParameter(CVTotalTransactionsCount,8)
DEBUG - After sending New Relic values: Current Thread Id: 9
每New Relic的警告日誌,我應該在調用線程ID的AddCustomParameter
方法5.
AddPoliciesCountInNewRelic
和AddTotalTransactionsCountInNewRelic
調用ApiControllerBase.AddNewRelicParameter(string, string)
基類的保護方法。
private void AddPoliciesCountInNewRelic(int policiesCount)
{
AddNewRelicParameter("CVPoliciesCount", policiesCount.ToString());
}
private void AddTotalTransactionsCountInNewRelic(int transactionsCount)
{
AddNewRelicParameter("CVTotalTransactionsCount", transactionsCount.ToString());
}
protected void AddNewRelicParameter(string key, string value)
{
if (!string.IsNullOrWhiteSpace(key) &&
!string.IsNullOrWhiteSpace(value))
{
try
{
NewRelic.Api.Agent.NewRelic.AddCustomParameter(key, value);
}
catch (Exception ex)
{
Log.Error($"ERROR! : New Relic Parameter Exception {ex}");
}
}
}
https://discuss.newrelic.com/t/are-custom-params-supported-in-async-mode/37601 <他們聲稱現在支持異步控制器。 – Evk
asp.net中的'ConfigureAwait(true)'並不能保證你回到開始調用的那個線程,就像你在Winforms或WPF中使用UI線程時一樣。 –
實際上'ConfigureAwait(true)'是默認行爲。它和'等待ReportService.GetReportAsync(requestModel);'完全一樣。 –