簡體   English   中英

任務運行異步時處置對象

[英]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 只會使 fp不再被視為GC根...盡管除非您稍后在代碼中對其進行其他任何處理,否則fp不會被視為GC根。

異步操作仍然具有對其調用對象的引用。 如果它使用任何字段,則將防止垃圾回收對象。 如果不是這樣,則引用的性質(可能通過回調中的委托) 可能會阻止它反正被垃圾回收,但是值得注意的是,當實例方法被使用時,有可能對對象進行垃圾回收。在其中運行。

但是這里沒有什么可以停止任務或異步方法,沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM