Skip to content

Instantly share code, notes, and snippets.

@Keboo
Last active Mar 12, 2019
Embed
What would you like to do?
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