Created
June 27, 2017 23:55
-
-
Save sinairv/0b5566d314a1013644281fe629d904a0 to your computer and use it in GitHub Desktop.
ThreadStatic demo
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; | |
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