Dispose an object while a task is running async

Viewed 2830

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.

1 Answers
Related