Skip to content

Instantly share code, notes, and snippets.

@Keboo
Last active March 12, 2019 06:05
Show Gist options
  • Save Keboo/c3bac6e9be8afa9d81a9ef01e6c83199 to your computer and use it in GitHub Desktop.
Save Keboo/c3bac6e9be8afa9d81a9ef01e6c83199 to your computer and use it in GitHub Desktop.
AsyncLocal
public class Person
{
public string Name { get; set; }
}
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
private static AsyncLocal<Person> LocalPerson { get; } = new AsyncLocal<Person>();
private static ThreadLocal<Person> ThreadPerson { get; } = new ThreadLocal<Person>();
public static async Task Main(string[] args)
{
LocalPerson.Value = new Person { Name = "John" };
ThreadPerson.Value = new Person { Name = "Jane" };
await BeBobAndSara();
await PrintPerson();
}
private static async Task BeBobAndSara()
{
await Task.Delay(0);
LocalPerson.Value = new Person { Name = "Bob" };
ThreadPerson.Value = new Person { Name = "Sara" };
}
private static async Task PrintPerson()
{
await Task.Delay(0);
Console.WriteLine(LocalPerson.Value?.Name);
Console.WriteLine(ThreadPerson.Value?.Name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment