Last active
March 12, 2019 06:05
-
-
Save Keboo/c3bac6e9be8afa9d81a9ef01e6c83199 to your computer and use it in GitHub Desktop.
AsyncLocal
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 class Person | |
{ | |
public string Name { get; set; } | |
} |
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
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