Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Async memory leak

$
0
0
The code below is a simple async sample but over time it leaks memory. Would anyone have any suggestions as to why?
using System;
using System.Threading;
using System.Threading.Tasks;
namespace CrazyAsync
{
    class Foo
    {
        public Func<CancellationToken, Task> Work;
        public async Task DoWork(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
                await Work?.Invoke(token);
        }
    }
    class Mamamia
    {
        public Task DoIt(CancellationToken token)
        {
            var t = Task.Delay(6, token);
            t.ContinueWith(x => 
            {
                if (x.Status == TaskStatus.Faulted)
                    Console.WriteLine(x.Exception.InnerException);
                if (i++ % 100 == 0)
                {
                    GC.Collect();
                    Program.DumpMemory();
                }
            });
            return t;
        }
        int i = 0;
    }
    class Program
    {
        static async Task Main(string[] args)
        {
            var cc = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var m = new Mamamia();
            var foo = new Foo()
            {
                Work = m.DoIt,
            };
            await foo.DoWork(cc.Token);
        }
        public static void DumpMemory()
        {
            var m = Environment.WorkingSet;
            Console.WriteLine($"Mem: {m:#,###}");
        }
    }
}


Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>