I have the following code:
public class Program
{
private static Task task;
private static int counter = 0;
private static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (task == null)
{
Console.WriteLine(++counter);
}
using (task = new Task(Method))
{
task.Start();
task.Wait();
}
// task = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
Console.ReadKey();
}
public static void Method() { }
}
My excepted output: 1 2 3 4 5 6... but the real output from this method is 1!
If I remove the comment from the code line Task = null;
then I will became the expected result.
Why the disposed tasks are not null!? I thought, if the objects are disposed then they can be set to null from the GC (I have forced the GC to collect) in other words the GC will collect the disposed(orphan) objects and put them to null?!