http://blogs.clariusconsulting.net/kzu

Daniel Cazzulino's Blog

Go Back to
kzu′s Latest post

Strong-typed access to Thread and AppDomain shared and transient state

Thread.SetData and AppDomain.SetData are sometimes quite useful, when you need to pass state out of band that is shared across an entire call stack in a thread or by an entire app domain.

But these APIs, like many others from .NET v1, are showing their age: they don’t have generic versions. In the spirit of a true NETFx NuGet, I made to nugets that give you these generic versions in convenient source code form (as all other NETFx extensions).

Here’s a unit test that shows how to use it:

[Fact]
public void WhenDataIsSet_ThenCanRetrieveIt()
{
    var data = new Foo { Id = 5 };

    using (AppDomain.CurrentDomain.SetData(data))
    {
        var saved = AppDomain.CurrentDomain.GetData<Foo>();

        Assert.Same(data, saved);
    }
}

Notice that the SetData returns a disposable that you can use to deterministically remove the data from the AppDomain.

Same API and usage applies to Thread.SetData<T>:

[Fact]
public void WhenDisposableIsDisposed_ThenDataIsRemoved()
{
    var data = new Foo { Id = 5 };

    using (Thread.CurrentThread.SetData(data))
    {
    }

    var saved = Thread.CurrentThread.GetData<Foo>();

    Assert.Null(saved);
}

And because you may need one or the other independently, I made them two nugets for your granular source code reuse pleasure. Just search for AppDomainData or ThreadData in the Library Package Reference dialog:

image

Comments

2 Comments

  1. There is generic class ThreadLocal in .NET 4. I know it is slightly different from what you are describing. Just it is a standard .NET class for storing thread-specific content.

  2. Yup, I know about ThreadLocal, but its storage algorithm is significantly different: each instance of it has its own storage slot, and it can’t be reused across boundaries unless you pass the ThreadLocal around, defeating the purpose of using TLS for passing out of band context data.