-3

What is the difference in using asyn/await vs await task.run()

await task.run example -

 public static void Main()
{

   await Task.Run(() =>
    {
        return "Good Job";
    });
    method1();
    method2();
}

Async await example-

 public static async void Launch()
    {

        await GetMessage();
        Method1();
        Method2();
    }

    public static async Task<string> GetMessage()
    {
        //Do some stuff
    }
  • This resource can be helpful: https://stackoverflow.com/questions/38739403/await-task-run-vs-await-c-sharp – Tearth Feb 26 '20 at 01:41
  • https://stackoverflow.com/questions/18013523/when-correctly-use-task-run-and-when-just-async-await and https://stackoverflow.com/questions/38739403/await-task-run-vs-await-c-sharp and https://stackoverflow.com/questions/50004373/understanding-async-await-and-task-run and https://stackoverflow.com/questions/36606519/async-await-vs-task-run-in-c-sharp – TheGeneral Feb 26 '20 at 01:57
  • 3
    Does this answer your question? [When correctly use Task.Run and when just async-await](https://stackoverflow.com/questions/18013523/when-correctly-use-task-run-and-when-just-async-await) – Eugene Feb 26 '20 at 01:59

1 Answers1

0

The difference is in the context in which the code will be run. return "Good Job"; will be executed instantly in the separate task (and possibly on the separate thread - this is determined by the default task scheduler, like ThreadPool). In the second one, all code in GetMessage before the first await will be executed synchronously, in the same context as the caller. The rest of the code after await will be delegated to the separate task.

Tearth
  • 286
  • 2
  • 8