线程返回ThreadPool时清除ThreadLocal数据

时间:2014-10-02 18:21:43

标签: .net wcf threadpool thread-local

我看了几个类似问题的网页,但没有人发布工作解决方案。所以我在这里试试运气。

我有一个简单的应用程序,当工作线程返回给ThreadPool时,我需要清除ThreadLocal数据。

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();
    }

}

当然如果每次一切都工作得很好,我就会创建自己的主题,而且我从未见过#34; old&#34;我的ThreadLocal数据中的数据。但是如果我使用来自线程池的线程我有一个问题 - 我可以看到过去的数据。因此,我需要找到一种方法来清除它们。

我在我的WCF应用程序中注意到了这个问题,其中来自ThreadPool的线程用于处理服务请求。因此,如果对我的WCF服务的一次调用在ThreadLocal中存储某些内容,则另一个调用(将使用相同的线程进行处理)可以访问它。我想可以通过在我的服务上可以访问的所有函数中调用一些清除函数来解决它。但这是唯一的解决方案吗?

由于

0 个答案:

没有答案