简体   繁体   中英

Async all the way vs. Task.Run on a simple calculation method

I've started to dive into aync programming and I want to execute a very simple add method as an async operation.

One of the things i've read is that truly async program does not require thread switching => that means Task.Run(..) can be avoided.

This is how I've implemented an add method:

public class TaskSimpleExample
    {
        public static void SimpleCalcExample()
        {
            // Will perform in background
            Task<int> resultTask = Task.Run(() => BeginCalcNumbers(6, 6));
            Console.WriteLine("Doing Work");
            Console.WriteLine("Doing More Work");
            Console.WriteLine("Doing Extra Work");
            resultTask.Wait();
            Console.WriteLine("Work is done!");
        }

        static int BeginCalcNumbers(int number1, int number2)
        {
            int result = Add(number1, number2);
            Console.WriteLine(result);
            return result;
        }

        static int Add(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }
    }

Unfortunately, I understand that it has nothing to do with async . It just opens another thread and runs in the background.

I've failed to convert this code to use async & await (and eliminate Task.Run ). Is it possible ? (Please notice I need to continue after the callback in other place in the method using resultTask.Wait() ).

What you know about Task.Run is absolutely correct and that's pretty much the point of using Task.Run

Using Task.Run will execute a method on a thread pool thread and return a task that represents the completion of the method.

As Stepthen Cleary suggest, you should use Task.Run only to call CPU-bound methods.

Another important thing to mention is that you should use Task.Run to actually call the method that does heavy CPU-bound work and not use Task.Run in the implementation of the method.

Here's a good example on how to use Task.Run properly:

class MyService
{
  public int CalculateMandelbrot()
  {
    // Tons of work to do in here!
    for (int i = 0; i != 10000000; ++i)
      ;
    return 42;
  }
}

...

private async void MyButton_Click(object sender, EventArgs e)
{
  await Task.Run(() => myService.CalculateMandelbrot());
}

Also you should read Task.Run Etiquette and Proper Usage and Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation if you are interested in learning more about Task.Run

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