Skip to content

Instantly share code, notes, and snippets.

@TsuyoshiUshio
Created September 13, 2024 04:29
Show Gist options
  • Save TsuyoshiUshio/9d0510c5eaa7486450552b20cb1ac7b2 to your computer and use it in GitHub Desktop.
Save TsuyoshiUshio/9d0510c5eaa7486450552b20cb1ac7b2 to your computer and use it in GitHub Desktop.
Custom ActivityTracker for Custom ActivityId
using System.Diagnostics.Tracing;
class Program
{
static void Main(string[] args)
{
HandleRequest(Guid.NewGuid());
}
static void HandleRequest(Guid activityId)
{
Console.WriteLine("Starting request with ID: " + activityId);
MyActivityTracker.SetActivityId(activityId);
DoSomeWork();
Task.Run(() => DoSomeWork());
MyActivityTracker.SetActivityId(Guid.Empty);
}
static void DoSomeWork()
{
Console.WriteLine($" ThreadId: {Thread.CurrentThread.ManagedThreadId} ActivityId: {EventSource.CurrentThreadActivityId}");
}
}
static class MyActivityTracker
{
static AsyncLocal<Guid> _activityId = new AsyncLocal<Guid>(ActivityIdChanged);
public static void SetActivityId(Guid activityId)
{
_activityId.Value = activityId;
}
private static void ActivityIdChanged(AsyncLocalValueChangedArgs<Guid> args)
{
EventSource.SetCurrentThreadActivityId(args.CurrentValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment