Bug 15036 - Entire Task.ContinueWith chains remain kept alive by final reference
Summary: Entire Task.ContinueWith chains remain kept alive by final reference
Alias: None
Product: Class Libraries
Classification: Mono
Component: mscorlib (show other bugs)
Version: 3.2.x
Hardware: PC Windows
: --- normal
Target Milestone: Untriaged
Assignee: Marek Safar
Depends on:
Reported: 2013-09-27 10:17 UTC by Weeble
Modified: 2013-10-09 06:52 UTC (History)
2 users (show)

See Also:
Is this bug a regression?: ---
Last known good build:


Description Weeble 2013-09-27 10:17:03 UTC
When a long chain of tasks are created with Task.ContinueWith, it appears that none of them are eligible for collection so long as the last task in the chain remains alive. This is different from the behaviour in .NET.

This example program rapidly allocates more and more memory under Mono (as viewed via top), whereas it soon plateaus under .NET on Windows (as viewed in Process Explorer).

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

class Program
    static void Main()
        var task = Task.Factory.StartNew(()=>0);
        while (true)
            for (int i=0; i!=100000; ++i)
                task = task.ContinueWith(
                    t => {
                        int count = t.Result + 1;
                        if (count==777773)
                            count = 0;
                        return count;

This is a problem if the task callbacks keep large objects alive or in a usage pattern that continuously adds new tasks to the end of a chain with ContinueWith.

Disposing each task does not help.

Looking at the implementation of Task, it appears that Task has a readonly field contAncestor that contains a reference to the task that it was created from with .ContinueWith(...). This would imply that it is impossible for the ancestor task to be garbage collected until all descendant tasks are eligible for collection. Perhaps it should be made mutable and nulled out in Task.Finish. I don't think there's any further use for it, and it should break the chain to allow collection of the ancestor task objects and everything else that they are keeping alive.

Comment 1 Marek Safar 2013-10-09 06:52:30 UTC
Fixed in master

Note You need to log in before you can comment on or make changes to this bug.