18

Say I have the following class:

class SomeClass
{
    private TaskCompletionSource<string> _someTask;

    public Task<string> WaitForThing()
    {
        _someTask = new TaskCompletionSource<string>();
        return _someTask.Task;
    }

    //Other code which calls _someTask.SetResult(..);
}

Then elsewhere, I call

//Some code..
await someClassInstance.WaitForThing();
//Some more code

The //Some more code won't be called until _someTask.SetResult(..) is called. The calling-context is waiting around in memory somewhere.

However, let's say SetResult(..) is never called, and someClassInstance stops being referenced and is garbage collected. Does this create a memory leak? Or does .Net auto-magically know the calling-context needs to be disposed?

1
  • A TCS is an isolated object. When it is unreachable it gets collected. Its Task does not reference the TCS so you can have an uncompletable Task without any corresponding TCS in memory. If that Task is unreferenced as well it is collected, too.
    – usr
    Commented Feb 1, 2015 at 9:48

2 Answers 2

9

Updated, a good point by @SriramSakthivel, it turns out I've already answered a very similar question:

Why does GC collects my object when I have a reference to it?

So I'm marking this one as a community wiki.

However, let's say SetResult(..) is never called, and someClassInstance stops being referenced and is garbage collected. Does this create a memory leak? Or does .Net auto-magically know the calling-context needs to be disposed?

If by the calling-context you mean the compiler-generated state machine object (which represents the state of the async method), then yes, it will indeed be finalized.

Example:

static void Main(string[] args)
{
    var task = TestSomethingAsync();
    Console.WriteLine("Press enter to GC");
    Console.ReadLine();
    GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
    GC.WaitForFullGCComplete();
    GC.WaitForPendingFinalizers();
    Console.WriteLine("Press enter to exit");
    Console.ReadLine();
}

static async Task TestSomethingAsync()
{
    using (var something = new SomeDisposable())
    {
        await something.WaitForThingAsync();
    }
}

class SomeDisposable : IDisposable
{
    readonly TaskCompletionSource<string> _tcs = new TaskCompletionSource<string>();

    ~SomeDisposable()
    {
        Console.WriteLine("~SomeDisposable");
    }

    public Task<string> WaitForThingAsync()
    {
        return _tcs.Task;
    }

    public void Dispose()
    {
        Console.WriteLine("SomeDisposable.Dispose");
        GC.SuppressFinalize(this);
    }
}

Output:

Press enter to GC

~SomeDisposable
Press enter to exit

IMO, this behavior is logical, but it still might be a bit unexpected that something gets finalized despite the fact that the using scope for it has never ended (and hence its SomeDisposable.Dispose has never been called) and that the Task returned by TestSomethingAsync is still alive and referenced in Main.

This could lead to some obscure bugs when coding system-level asynchronous stuff. It's really important to use GCHandle.Alloc(callback) on any OS interop callbacks which are not referenced outside async methods. Doing GC.KeepAlive(callback) alone at the end of the async method is not effective. I wrote about this in details here:

Async/await, custom awaiter and garbage collector

On a side note, there's another kind of C# state machine: a method with return yield. Interestingly, along with IEnumerable or IEnumerator, it also implements IDisposable. Invoking its Dispose will unwind any using and finally statements (even in the case of incomplete enumerable sequence):

static IEnumerator SomethingEnumerable()
{
    using (var disposable = new SomeDisposable())
    {
        try
        {
            Console.WriteLine("Step 1");
            yield return null;
            Console.WriteLine("Step 2");
            yield return null;
            Console.WriteLine("Step 3");
            yield return null;
        }
        finally
        {
            Console.WriteLine("Finally");
        }
    }
}
// ...
var something = SomethingEnumerable();
something.MoveNext(); // prints "Step 1"
var disposable = (IDisposable)something;
disposable.Dispose(); // prints "Finally", "SomeDisposable.Dispose"

Unlike this, with async methods there's no direct way of controlling the unwiding of using and finally.

3
  • How do you know "the compiler-generated state machine object" is guaranteed to be disposed when the object is finalized, though? Commented Feb 1, 2015 at 7:04
  • @BlueRaja-DannyPflughoeft, what do you mean under "be disposed" here? The state machine object doesn't implement IDisposable. It's just a boxed struct, but all of its fields (like something above) do get garbage-collected and finalized (note how ~SomeDisposable gets invoked) - because the struct itself gets GC'ed.
    – noseratio
    Commented Feb 1, 2015 at 7:49
  • @SriramSakthivel, thanks for your point about a duplicate, I've marked this one as a wiki.
    – noseratio
    Commented Feb 2, 2015 at 5:00
6

You should ensure your tasks are always completed.

In the usual case, the "Other code which calls SetResult" is registered as a callback somewhere. E.g., if it's using unmanaged overlapped I/O, then that callback method is a GC root. Then that callback explicitly keeps _someTask alive, which keeps its Task alive, which keeps the delegate for //Some more code alive.

If the "Other code which calls SetResult" is not (directly or indirectly) registered as a callback, then I don't think there will be a leak. Note that this is not a supported use case, so this is not guaranteed. But I did create a memory profiling test using the code in your question and it does not appear to leak.

2
  • So it depends on where the "other code" is? I'm confused on how to tell which cases will leak... My use-case is that WaitForThing() waits for user input from a user on the other end of an IM client (and is called from the object that represents a "friend") and returns it. However, if that user is removed as a friend, that input can never occur - there is no way for me to "complete" it. Commented Feb 1, 2015 at 0:25
  • 1
    @BlueRaja-DannyPflughoeft: I recommend that you complete the task as canceled (SetCanceled) when the user is removed as a friend. Commented Feb 1, 2015 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.