Last active
August 29, 2015 14:15
-
-
Save i3arnon/06f4c84711c88f6ce04b to your computer and use it in GitHub Desktop.
LogicalOperationStack (purely hypothetical)
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
public static class MyStack | |
{ | |
private static Stack CurrentContext | |
{ | |
get | |
{ | |
return Trace.CorrelationManager.LogicalOperationStack; | |
} | |
} | |
public static IDisposable Push(string context) | |
{ | |
CloneAndSetStack(); | |
Trace.CorrelationManager.StartLogicalOperation(context); | |
return new PopWhenDisposed(); | |
} | |
private static void CloneAndSetStack() | |
{ | |
CallContext.LogicalSetData("System.Diagnostics.Trace.CorrelationManagerSlot", CurrentContext.Clone()); | |
} | |
private static void Pop() | |
{ | |
Trace.CorrelationManager.StopLogicalOperation(); | |
} | |
private sealed class PopWhenDisposed : IDisposable | |
{ | |
private bool disposed; | |
public void Dispose() | |
{ | |
if (disposed) | |
return; | |
Pop(); | |
disposed = true; | |
} | |
} | |
public static string CurrentStack | |
{ | |
get | |
{ | |
return string.Join(" ", CurrentContext.Cast<string>().Reverse()); | |
} | |
} | |
} |
Just so you know, it is not necessary to change "System.Diagnostics.Trace.CorrelationManagerSlot". To trigger the copy-on-write, you just need to touch any item in the context. You could have something like that to avoid unnecessary allocations:
private static readonly object Flag = new object();
...
CallContext.LogicalSetData("Flag7645", Flag);
Trace.CorrelationManager.StartLogicalOperation(operationId);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
StartLogicalOperation
updates the underlyingStack
i.e. the parent context'sStack
since no copy has happened yet to the new child context.CloneAndSetStack
generates the copy-on-write thatStartLogicalOperation
doesn't.