在任务 运行 异步时处置对象

Dispose an object while a task is running async

考虑以下场景...

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();
    }
}

调用 dispose 并将对象引用设置为 null 后,任务 运行 会完成吗?

OnNext 方法不依赖于释放的任何资源。

处置没有什么神奇之处。 Dispose 方法被调用 - 如果您没有影响任务使用的任何东西,那应该没问题。

同样将 fp 设置为 null just 阻止 fp 被视为 GC 根...尽管除非你正在做任何其他事情稍后在代码中,fp 无论如何都不会被视为 GC 根。

异步操作仍有对其调用对象的引用。如果它使用任何字段,这将阻止对象被垃圾收集。如果没有,引用的性质(可能通过回调中的委托)将 可能 阻止它被垃圾收集,但值得一提的是当实例方法是 运行 "in" 时对象将被垃圾收集。

但是这里没有任何东西可以停止任务或异步方法,不。