Dispose an object while a task is running async

Consider the following scenario...

class FileProcessor : IDisposable
{
    public void Dispose()
    {
        //Disposes resources.
    }

    public async void OnNext(string fileName)
    {
        await Task.Run(() =>
        {
            var lines = File.ReadLines(fileName);
            //long processing with the lines...
        });
    }
}

class Program
{
    static void Main(string[] args)
    {
        var fp = new FileProcessor();
        fp.OnNext("some file");
        fp.OnNext("some file");

        //dispose is called and the object reference is set to null.
        fp.Dispose();
        fp = null;

        //..but the async tasks are still running...

        //Will they run to completion no matter how long they take? 

        Console.ReadKey();
    }
}

upon calling dispose and setting the object reference to null, will the tasks run to completion?

The OnNext method does not depend on any resources that are disposed.

Jon Skeet
people
quotationmark

There's nothing magic about disposal. The Dispose method is called - if you're not affecting anything that the tasks use, that should be fine.

Likewise setting fp to null just stops fp from being treated as a GC root... although unless you're doing anything else with it later in the code, fp wouldn't be treated as a GC root anyway.

The asynchronous operation still has a reference to the object it's called on. If it uses any of the fields, that will prevent the object from being garbage collected. If it doesn't, the nature of the reference (probably via a delegate in a callback) will probably stop it from being garbage collected anyway, but it's worth being aware that it's possible for an object to be garbage collected while an instance method is running "in" it.

But there's nothing here that would stop the task or the asynchronous methods, no.

people

See more on this question at Stackoverflow