AsyncLocal
This file contains 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 class Person | |
{ | |
public string Name { get; set; } | |
} |
This file contains 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; | |
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