Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AsyncLocal and immutable stack state

Technically in this example you don't need to pop from the stack - the state will automatically get restored to the parent's context when the call completes, I only include it for completeness.

root, B1, C1
root, B2, C2
root, B1
root, B2
root
using System;
using System.Threading;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
public class Program
{
private static AsyncLocal<ImmutableStack<string>> stack = new AsyncLocal<ImmutableStack<string>>();
public static void Main()
{
stack.Value = ImmutableStack<string>.Empty.Push("root");
var t1 = Run(1);
var t2 = Run(2);
Task.WhenAll(t1, t2).GetAwaiter().GetResult();
WriteStack();
}
private static Task Run(int i)
{
return Task.Run(async () =>
{
stack.Value = stack.Value.Push("B" + i);
await Task.Run(() =>
{
stack.Value = stack.Value.Push("C" + i);
Thread.Sleep(50);
WriteStack();
stack.Value = stack.Value.Pop();
});
Thread.Sleep(50);
WriteStack();
stack.Value = stack.Value.Pop();
});
}
private static void WriteStack()
{
Console.WriteLine(String.Join(", ", stack.Value.Reverse()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment