@@ -48,7 +48,8 @@ public void BeginRequest(HttpContext httpContext, ref HostingApplication.Context
48
48
49
49
if ( loggingEnabled || ( diagnosticListenerEnabled && _diagnosticListener . IsEnabled ( ActivityName , httpContext ) ) )
50
50
{
51
- context . Activity = StartActivity ( httpContext ) ;
51
+ context . Activity = StartActivity ( httpContext , out var hasDiagnosticListener ) ;
52
+ context . HasDiagnosticListener = hasDiagnosticListener ;
52
53
}
53
54
54
55
if ( diagnosticListenerEnabled )
@@ -132,7 +133,7 @@ public void RequestEnd(HttpContext httpContext, Exception exception, HostingAppl
132
133
// Always stop activity if it was started
133
134
if ( activity != null )
134
135
{
135
- StopActivity ( httpContext , activity ) ;
136
+ StopActivity ( httpContext , activity , context . HasDiagnosticListener ) ;
136
137
}
137
138
138
139
if ( context . EventLogEnabled && exception != null )
@@ -229,9 +230,10 @@ private static void RecordRequestStartEventLog(HttpContext httpContext)
229
230
}
230
231
231
232
[ MethodImpl ( MethodImplOptions . NoInlining ) ]
232
- private Activity StartActivity ( HttpContext httpContext )
233
+ private Activity StartActivity ( HttpContext httpContext , out bool hasDiagnosticListener )
233
234
{
234
235
var activity = new Activity ( ActivityName ) ;
236
+ hasDiagnosticListener = false ;
235
237
236
238
var headers = httpContext . Request . Headers ;
237
239
if ( ! headers . TryGetValue ( HeaderNames . TraceParent , out var requestId ) )
@@ -266,6 +268,7 @@ private Activity StartActivity(HttpContext httpContext)
266
268
267
269
if ( _diagnosticListener . IsEnabled ( ActivityStartKey ) )
268
270
{
271
+ hasDiagnosticListener = true ;
269
272
_diagnosticListener . StartActivity ( activity , new { HttpContext = httpContext } ) ;
270
273
}
271
274
else
@@ -277,9 +280,16 @@ private Activity StartActivity(HttpContext httpContext)
277
280
}
278
281
279
282
[ MethodImpl ( MethodImplOptions . NoInlining ) ]
280
- private void StopActivity ( HttpContext httpContext , Activity activity )
283
+ private void StopActivity ( HttpContext httpContext , Activity activity , bool hasDiagnosticListener )
281
284
{
282
- _diagnosticListener . StopActivity ( activity , new { HttpContext = httpContext } ) ;
285
+ if ( hasDiagnosticListener )
286
+ {
287
+ _diagnosticListener . StopActivity ( activity , new { HttpContext = httpContext } ) ;
288
+ }
289
+ else
290
+ {
291
+ activity . Stop ( ) ;
292
+ }
283
293
}
284
294
}
285
295
}
0 commit comments