A little riddle with AsyncLocal
--
Children have a very accurate sense of curiosity. For them, everything is new and the smallest things can trigger the spark of wanting to know more and understand what something is. This is more commonly called Curiosity.
“We learn more by looking for the answer to a question and not finding it than we do from learning the answer itself.” — Lloyd Alexander
Much like children’s curiosity spark can be triggered with a new awesome monocular enabling them hours and hours of fun, a Software Engineer like myself can have this same spark triggered by a couple of simple lines of code.
Some weeks ago, I was debugging my code and I came across one of these situations where I felt like a child that just got a new awesome toy. I was struck by curiosity wanting to know how some simple lines of code I had on my screen worked.
For the sake of simplicity, I made this simple code snippet that can illustrate the code and its behavior. And now I have a challenge for you reading this blogpost! Can you know what will be printed in the console after running these simple lines of code?
Do you think you know the output of this code? Keep your answers close, let’s get started with the dissection of this code to understand what’s really happening here!
Once I first saw this piece of code I was pretty sure that I knew what the output would be, but I couldn’t be more wrong! The moment I ran the code and saw the output the curiosity spark lighted up!
The king of this show is the class AsyncLocal, here we have a property using this class named _asyncLocal
, so what’s special about AsyncLocal<T>
?
AsyncLocal
class allow asynchronous code to use a kind ofasync
-compatible almost-equivalent of thread local…