سؤال

I am trying to get some insight into how Timer will use thread pool. I wrote following simple snippet.

class Program
    {
        static private readonly Action Action = () => {
                                                     Thread.SpinWait(100 * 10000);
                                                     Interlocked.Increment(ref _data);
        };

        private static volatile int _data;

        static private Timer _threadCountChecker = new Timer(
            (obj) =>
                {
                    var t = Process.GetCurrentProcess().Threads;
                    Console.WriteLine("Using {0} threads.", t.Count);
                    Console.WriteLine(Program._data);
                }, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

        static void Main(string[] args)
        {
            var l = new List<Timer>();

            for (int i = 0; i < 10; i++)
            {
                l.Add(new Timer((obj) => Action(), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)));
            }

            var exitEvent = new ManualResetEvent(false);
            exitEvent.WaitOne();
        }
    }

Surprisingly this is the output I get:

Using 14 threads. 10 Using 14 threads. 18 Using 14 threads. 28 Using 14 threads. 39 Using 14 threads. 48 Using 15 threads. 58 Using 15 threads. 69 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80 Using 15 threads. 80

The data variable stays at 80 no matter for how long I keep running the process.

Does anyone have an idea why the variable gets updated for the first 8 iteration and just stops being incremented?

هل كانت مفيدة؟

المحلول

The timers got garbage collected. Add this statement after the eventWait.WaitOne() call to fix that:

  GC.KeepAlive(l);

The way the GC treats local variables in the Release build is explained in detail in this answer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top