Skip to content

Instantly share code, notes, and snippets.

@sinairv
Created June 27, 2017 23:55
Show Gist options
  • Save sinairv/0b5566d314a1013644281fe629d904a0 to your computer and use it in GitHub Desktop.
Save sinairv/0b5566d314a1013644281fe629d904a0 to your computer and use it in GitHub Desktop.
ThreadStatic demo
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStaticDemo
{
public class Program
{
public static void Main(string[] args)
{
PrintDescription("Before assignment");
SomeScope.ScopeDescription = "Desc01";
PrintDescription("After assignment");
Task.Run(() =>
{
PrintDescription("Before assignment");
SomeScope.ScopeDescription = "Desc02";
PrintDescription("After assignment");
}).GetAwaiter().GetResult();
Console.WriteLine("Press a key...");
Console.ReadLine();
}
static void PrintDescription(string message)
{
Console.WriteLine($"{message} [Thread: {Thread.CurrentThread.ManagedThreadId}]: " + (SomeScope.ScopeDescription ?? "[null]"));
}
}
public class SomeScope
{
// Try commenting the attribute out and see the difference
[ThreadStatic]
public static string ScopeDescription;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment