Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose properly using async and await

I'm trying to make code replacement from Thread to Task. The sleep / delay is just representing long running activity.

static void Main(string[] args)
{
    ThreadDoWork();
    TaskDoWork();
}
public static void ThreadDoWork()
{
    using (var dispose = new ThreadDispose())
    {
        dispose.RunAsync();
    }
}
public static async void TaskDoWork()
{
    using (var dispose = new TaskDispose())
    {
        await dispose.RunAsync();
    }
}
public class ThreadDispose : IDisposable
{
    public void RunAsync ()
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            Thread.Sleep(3000);
        });
    }
    void IDisposable.Dispose()
    {
        File.AppendAllText("D:\\test.txt", "thread disposing");
    }
}
public class TaskDispose : IDisposable
{
    public async Task RunAsync()
    {
        await Task.Delay(3000);
    }
    void IDisposable.Dispose()
    {
        File.AppendAllText("D:\\test.txt", "task disposing");
    }
}

The result after 3 seconds in test.txt is only

thread disposing

What do I need to change in order TaskDispose::Dispose is always executed just like ThreadDispose?

like image 362
Yuliam Chandra Avatar asked Aug 03 '14 16:08

Yuliam Chandra


People also ask

Is it mandatory to use await with async?

An async function without an await expression will run synchronously. The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.

Does await throw exception?

If we use the “await” keyword, the exception will be thrown: This solves the problem for a single simple task, but what if we have multiple tasks running within a method?

Why should one call GC SuppressFinalize when implementing Dispose method?

Dispose should call GC. SuppressFinalize so the garbage collector doesn't call the finalizer of the object. To prevent derived types with finalizers from having to reimplement IDisposable and to call it, unsealed types without finalizers should still call GC.


1 Answers

Let's isolate each piece of code:

public static void ThreadDoWork()
{
    using (var dispose = new ThreadDispose())
    { 
        dispose.RunAsync();
    }
}

public void RunAsync()
{
    ThreadPool.QueueUserWorkItem(state =>
    {
        Thread.Sleep(3000);
    });
}

What you do in this first piece of code is queue work on a threadpool thread. Because you're running this code inside a using scope and it runs asynchronously on a different thread, it disposes immediately. That is why you see the dispose message inside your text file.

public static async void TaskDoWork()
{
   using (var dispose = new TaskDispose())
   {
       await dispose.RunAsync();
   }
}

public class TaskDispose : IDisposable
{
   public async Task RunAsync()
   {
       await Task.Delay(3000);
   }
}

When you await inside your method, what you actually say is something along the lines of: "Execute this code. Because it's asynchronous by nature, I will return control back to the calling method, please call me back once you complete the asynchronous operation".

Your code hits the await keyword and returns control to your Main method. Inside Main, your async method is the last piece of code to execute, hence finishing your application, and not giving a chance for your Dispose method to execute.

If you want it to dispose, you'll have to change the return type from void to Task and explicitly Wait:

public static async Task TaskDoWork()
{
    using (var dispose = new TaskDispose())
    {
       await dispose.RunAsync();
    }
}

And now:

static void Main(string[] args)
{
    ThreadDoWork();
    TaskDoWork().Wait();
}

Side Note:

There are a couple of guidelines that should be followed:

  1. async void is for compatability with event handlers, there are rarely occasions outside that scope where it should be used. Instead, use async Task.

  2. Methods doing asynchoronous operation using TAP (Task Asynchronous Pattern) should end with the Async postfix. TaskDoWork should be TaskDoWorkAsync.

  3. Using Wait on a Task can cause deadlocks. In this particular case it doesn't because a console application doesn't have a SynchronizationContext and uses the threadpools. The recommended approach is to go "async all the way" and use await.

There is great reading material inside the async-await tag wiki, make sure to check it out.

like image 58
Yuval Itzchakov Avatar answered Sep 20 '22 08:09

Yuval Itzchakov