using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Threads
{
    // Listing 17-2
    public static class PerThreadCount
    {
        [ThreadStatic]
        private static int _count;

        public static int Count { get { return _count; } }

        public static void Increment()
        {
            _count += 1;
        }
    }

    class Example2
    {
        public static void UseThreadStatic()
        {
            Thread t1 = new Thread(Show);
            Thread t2 = new Thread(Show);
            t1.Start();
            Thread.Sleep(200);
            t2.Start();
            t1.Join();
            t2.Join();
        }

        private static void Show()
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("{0}: {1}", threadId, PerThreadCount.Count);
            PerThreadCount.Increment();
            Console.WriteLine("{0}: {1}", threadId, PerThreadCount.Count);
            Thread.Sleep(300);
            Console.WriteLine("{0}: {1}", threadId, PerThreadCount.Count);
            PerThreadCount.Increment();
            Console.WriteLine("{0}: {1}", threadId, PerThreadCount.Count);
        }
    }
}
