Skip to content

Commit 00d496d

Browse files
committed
Change how EndSegment is called for Tasks.
If the Task has already completed, we call EndSegment (synchronously) immediately. Otherwise, we always continue with TaskContinuationOptions.ExecuteSynchronously, which runs our continuation as soon as possible (on the thread that completed the task). This avoids task continuations being delayed until much later in the ASP.NET pipeline (due to when AspNetSynchronizationContext posts them), which causes inaccurate timings.
1 parent 03d6ca8 commit 00d496d

File tree

2 files changed

+7
-10
lines changed

2 files changed

+7
-10
lines changed

src/Agent/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Enables nullable reference types that are part of the C# 8.0 language specificat
1414

1515
### Fixes
1616
* Fixes an issue that may cause `InvalidCastException` due to an assembly version mismatch in Mvc3 instrumentation.
17+
* Fixes an async timing issue that can cause the end time of `Task`-returning methods to be determined incorrectly.
1718

1819
## [8.31] - 2020-08-17
1920
### New Features

src/Agent/NewRelic/Agent/Extensions/NewRelic.Agent.Extensions/Providers/Wrapper/Delegates.cs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -152,22 +152,18 @@ private static void OnSuccess<T>(Task task, IAgent agent, ISegment segment, bool
152152
transaction.Hold();
153153
}
154154

155-
if (options == TaskContinueWithOption.None)
155+
if (task.IsCompleted)
156+
{
157+
EndSegment(task);
158+
}
159+
else if (options == TaskContinueWithOption.None)
156160
{
157161
if (!continuationOptions.HasValue) task.ContinueWith(EndSegment);
158162
else task.ContinueWith(EndSegment, continuationOptions.Value);
159163
}
160164
else
161165
{
162-
var context = SynchronizationContext.Current;
163-
if (context != null)
164-
{
165-
task.ContinueWith(EndSegment, TaskScheduler.FromCurrentSynchronizationContext());
166-
}
167-
else
168-
{
169-
task.ContinueWith(EndSegment, TaskContinuationOptions.ExecuteSynchronously);
170-
}
166+
task.ContinueWith(EndSegment, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
171167
}
172168

173169
void EndSegment(Task completedTask)

0 commit comments

Comments
 (0)