5

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.

6
  • 1
    What have you found in your testing? You could easily figure this out by adding some write line calls or trace statements to your OnNext method. Commented Aug 8, 2017 at 8:38
  • Why don't you await fp.OnNext("some file")? It seems right to await for completion and then dispose this object. Commented Aug 8, 2017 at 8:39
  • AFAIK, since you run tasks using Task.Run, they are safely stored and will complete. Of course, I assume that you don't dispose any objects that this task needs to successfully complete. Commented Aug 8, 2017 at 8:40
  • @pstrjds I did run a test but on a short duration as I cannot spend hours testing my initial test cast. Commented Aug 8, 2017 at 8:48
  • @YeldarKurmangaliyev disposing of the object is not in my control. It really depends on the caller of my object. Commented Aug 8, 2017 at 8:50

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That is the perfect answer to my question.