Is CancellationTokenSource.CancelAfter() leaky?

后端 未结 1 505
南旧
南旧 2021-01-18 22:37

The release of the Async Targeting Pack prompted me to use ILSpy to have a look at what Task-based Asynchronous Pattern (TAP) extension methods were provided there (some of

相关标签:
1条回答
  • 2021-01-18 22:54

    Just try it, push it to the limits and see what happens. I can't get working set to go over 90 MB with ten million timers. System.Threading.Timer is very cheap.

    using System;
    using System.Threading;
    
    class Program {
        public static int CancelCount;
        static void Main(string[] args) {
            int count = 1000 * 1000 * 10;
            for (int ix = 0; ix < count; ++ix) {
                var token = new CancellationTokenSource();
                token.CancelAfter(500);
            }
            while (CancelCount < count) {
                Thread.Sleep(100);
                Console.WriteLine(CancelCount);
            }
            Console.WriteLine("done");
            Console.ReadLine();
        }
    }
    
    static class Extensions {
        public static void CancelAfter(this CancellationTokenSource source, int dueTime) {
            Timer timer = new Timer(delegate(object self) {
                Interlocked.Increment(ref Program.CancelCount);
                ((IDisposable)self).Dispose();
                try {
                    source.Cancel();
                }
                catch (ObjectDisposedException) {
                }
            });
            timer.Change(dueTime, -1);
        }
    }
    
    0 讨论(0)
提交回复
热议问题