简体   繁体   中英

Async/Await vs Threads Scenario

I'm new to C# and was wondering in which cases to use Async/Await and when to use threads as I understand that Async/Await do not create new threads.

For example, which of the two print methods below should be used if I want to schedule print hello every hour for the next ten hours?

    private async void PrintHelloAsync(int delay)
    {
        await Task.Delay(delay);
        Console.WriteLine("Hello");
    }

    private void PrintHelloThread(int delay)
    {
        Task.Run(async () =>
        {
            await Task.Delay(delay);
            Console.WriteLine("Hello");
        });
    }

Should I call PrintHelloAsync 10 times with increasing delays, or PrintHelloThread?

Am I even using these concurrency concepts correctly?

Right now I'm working on a project where I need to schedule a task at 6PM, 9PM, and Midnight and was trying to figure out the best way to do it.

The main difference between the two functions is that the first one is performed by the calling thread, while the second one is called by a free thread in the thread pool.

Someone on stackoverflow explained me once the difference using the metaphor (Alas I don't know his name anymore).

Suppose you want to make breakfast. You need to toast some bread and boil some eggs.

You could put some bread in the toaster, wait until the bread is toasted, remove the toasted bread from the toaster and start boiling water. Once the water boils you add the eggs, wait some time and remove the eggs from the water and put out the fire. This is a typical example of synchronous execution.

On the other hand, after you put the bread in the toaster, you could already start boiling water. Wait until either the bread is toasted or the water is boiling. In the first case you'll remove the bread and wait for the water to boil. In the latter case you'll put the eggs in the water and wait until either the bread is toasted or the eggs are ready. As soon as you have to await for something to happen you look around whether you can do something else to speed up the process: a typical example of asynchronous execution, but still performed by one thread. This is the method async-await uses, the method used by your first function.

The most expensive method is hire a cook who you will order to toast some bread while you start heating the water to boil some eggs: concurrent processing performed by several threads.

If you have a thread that has only one thing to do, it's not wise if that thread hires a cook to do the thing and let that thread wait until the cook is ready: why not let the thread do the thing?

So if your thread has nothing else to do, use your first function.

However this first function can only be called if your thread is running in an async function itself. If your thread is not in an async function and it can do something meaningful while your bread is being toasted, consider using your second method.

I assume that ultimately your goal is to schedule your tasks for 6PM, 9PM, etc. Without going into too much detail, you are probably heading down the wrong path (with delayed tasks and thinking about threads). Instead, I would recommend looking at a scheduler system - like Quartz.net or HangFire - hosted within a windows service, or simply using the windows task scheduler to start your application up at a specific time.

If you have no choice but to implement a scheduling system yourself, I would look at the System.Timers.Timer class as a start:

using System;
using System.Threading.Tasks;
using System.Timers;

class Example
{
    static void Main()
    {
        Timer timer = new Timer(1000);
        timer.Elapsed += async ( sender, e ) => await HandleTimer();
        timer.Start();
        Console.Write("Press any key to exit... ");
        Console.ReadKey();
    }

    private static Task HandleTimer()
    {
        Console.WriteLine("Timer event");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM