Skip to content

Instantly share code, notes, and snippets.

Created September 24, 2014 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3722bd3b3484ac75b06d to your computer and use it in GitHub Desktop.
Save anonymous/3722bd3b3484ac75b06d to your computer and use it in GitHub Desktop.
Example of thread-static context in .Net
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