I read few webpages with similar issue but nobody post working solution. Therefore I am trying my luck here.
I have simple application where I need to clear ThreadLocal data when worker thread is returned to ThreadPool.
class Program
{
private static readonly ThreadLocal<ThreadData> ThreadLocalData = new ThreadLocal<ThreadData>(() =>
{
Console.WriteLine("[{0}] ThreadLocal storage created", Thread.CurrentThread.ManagedThreadId);
return new ThreadData();
});
private class ThreadData
{
public readonly List<int> Ints = new List<int>();
}
private static void WorkerThreadWork()
{
Console.WriteLine("[{0}] WTW entered", Thread.CurrentThread.ManagedThreadId);
if (ThreadLocalData.IsValueCreated)
{
Console.WriteLine("[{0}] Value is already created!", Thread.CurrentThread.ManagedThreadId);
}
ThreadLocalData.Value.Ints.Add(DateTime.Now.Second);
if (ThreadLocalData.Value.Ints.Count > 1)
{
Console.WriteLine("[{0}] Count of values: {1}", Thread.CurrentThread.ManagedThreadId, ThreadLocalData.Value.Ints.Count);
}
}
static void Main(string[] args)
{
var dt = DateTime.Now;
for (int i = 0; i < 100; i++)
{
ThreadPool.QueueUserWorkItem(state => { WorkerThreadWork(); });
//Thread t = new Thread(() => { WorkerThreadWork(); });
//t.IsBackground = true;
//t.Start();
}
Console.WriteLine();
Console.WriteLine("Test duration: {0}", (DateTime.Now - dt).TotalMilliseconds);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
Of course If I will create my own thread each time everything is working great and I never meet "old" data in my ThreadLocal data. But if I use thread from threadpool I have an issue - I can see data from past. Thus I need to find a way how to clear them.
I noticed this issue in my WCF application where threads from ThreadPool are used for processing request on service. Thus if one call to my WCF service store something in ThreadLocal another call (which will use same thread for processing) can access it. I suppose it can be solved by calling some clear function in all functions which can be accessed on my service. But is it the only solution?
Thanks