Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ActivityRecorder more threadsafe #104888

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions src/libraries/Common/tests/System/Net/ActivityRecorder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Xunit;

namespace System.Net.Test.Common
Expand All @@ -17,12 +18,16 @@ internal class ActivityRecorder : IDisposable
private readonly ActivityListener _listener;
private List<Activity> _finishedActivities = new();

private int _started;
private int _stopped;

public int Started => _started;
public int Stopped => _stopped;

public Predicate<Activity> Filter { get; set; } = _ => true;
public bool VerifyParent { get; set; } = true;
public Activity ExpectedParent { get; set; }

public int Started { get; private set; }
public int Stopped { get; private set; }
public Activity LastStartedActivity { get; private set; }
public Activity LastFinishedActivity { get; private set; }
public IEnumerable<Activity> FinishedActivities => _finishedActivities;
Expand All @@ -35,34 +40,41 @@ public ActivityRecorder(string activitySourceName, string activityName)
{
ShouldListenTo = (activitySource) => activitySource.Name == _activitySourceName,
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllData,
ActivityStarted = (activity) => {
ActivityStarted = (activity) =>
{
if (activity.OperationName == _activityName && Filter(activity))
{
if (VerifyParent)
{
Assert.Same(ExpectedParent, activity.Parent);
}

Started++;
Interlocked.Increment(ref _started);

LastStartedActivity = activity;
}
},
ActivityStopped = (activity) => {
ActivityStopped = (activity) =>
{
if (activity.OperationName == _activityName && Filter(activity))
{
if (VerifyParent)
{
Assert.Same(ExpectedParent, activity.Parent);
}

Stopped++;
LastFinishedActivity = activity;
_finishedActivities.Add(activity);
Interlocked.Increment(ref _stopped);

lock (_finishedActivities)
{
LastFinishedActivity = activity;
_finishedActivities.Add(activity);
}
}
}
};

ActivitySource.AddActivityListener(_listener);
ActivitySource.AddActivityListener(_listener);
}

public void Dispose() => _listener.Dispose();
Expand Down