Created
September 13, 2024 04:29
-
-
Save TsuyoshiUshio/9d0510c5eaa7486450552b20cb1ac7b2 to your computer and use it in GitHub Desktop.
Custom ActivityTracker for Custom ActivityId
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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