Skip to main content
Removed tags from title
Link
Uwe Keim
  • 40.9k
  • 61
  • 193
  • 309

c# .net dispose Dispose an object while a task is running async

Source Link
user6465254
user6465254

c# .net 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.