Created
September 24, 2014 09:16
-
-
Save anonymous/3722bd3b3484ac75b06d to your computer and use it in GitHub Desktop.
Example of thread-static context in .Net
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; | |
namespace AsyncScope | |
{ | |
public class MyContext : IDisposable | |
{ | |
[ThreadStatic] private static MyContext CurrentContext; | |
private readonly int value; | |
private MyContext parentContext; | |
public MyContext(int value) | |
{ | |
this.value = value; | |
parentContext = CurrentContext; | |
CurrentContext = this; | |
} | |
public static int? Current | |
{ | |
get | |
{ | |
MyContext currentContext = CurrentContext; | |
return currentContext != null ? currentContext.value : (int?) null; | |
} | |
} | |
#region IDisposable Members | |
void IDisposable.Dispose() | |
{ | |
CurrentContext = parentContext; | |
parentContext = null; | |
} | |
#endregion | |
internal static void Clear() | |
{ | |
CurrentContext = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment