Async Quiz #1

Bnaya Eshet
1 min readApr 17, 2018

--

Assuming you have the following code snippet:

public class Factory
{
public static async Task<IDisposable> Create()
{
await Task.Delay(500);
return new Disposale();
}
}

public class Disposale : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposed)
{
if(disposed)
Console.WriteLine("Disposed :)");
else
Console.WriteLine("Disposed from Finalizer :(");
}
~Disposale()
{
Dispose(false);
}
}

What will be the output of the following code snippet?

static async Task ExecuteAsync(string[] args)
{
using (Factory.Create())
{
await Task.Delay(2000);
}
GC.Collect();
Console.ReadKey();
}

The answer is: Disposed from Finalizer :(

You shouldn’t forget to awit.

The following code will do the difference:

static async Task ExecuteAsync(string[] args)
{
using (await Factory.Create())
{
await Task.Delay(2000);
}
GC.Collect();
Console.ReadKey();
}

The previous code snippet is actually disposing the Task.

--

--