-1

I'm writing C# code with Visual Studio. I have a Task-returning function awaited in an async Task method like the following:

async Task AwaitForSomeTask()
{
    await DoSomething();
}

I wrote two possible implementations (provided below) of DoSomething() method. What are the differences between these two implementations? What are the advantages and/or disadvatages of each one?

Task DoSomething()
{
    return Task.Run( () => { // Some code } );
}

async Task DoSomething()
{
    // Some code
}

Thank you in advance!

Fra
  • 1
  • 1
  • [Task Class](https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx) [Task.Run Method (Action)](https://msdn.microsoft.com/en-us/library/hh195051(v=vs.110).aspx) I would recommend reading the [Async in C# 5.0](http://shop.oreilly.com/product/0636920026532.do) – rmjoia Sep 27 '17 at 10:43
  • Possible duplicate of [What is the purpose of "return await" in C#?](https://stackoverflow.com/questions/19098143/what-is-the-purpose-of-return-await-in-c) – quadroid Sep 27 '17 at 10:44
  • 1
    Possible duplicate of [Difference between calling an async method and Task.Run an async method](https://stackoverflow.com/questions/31958146/difference-between-calling-an-async-method-and-task-run-an-async-method) – Vijayanath Viswanathan Sep 27 '17 at 10:47

3 Answers3

0

async really means that you will use await inside your method. If you have no plans to do so, then you can just return Task without async keyword.

In any case you can do await on the calling method.

But it's quite unclear on what you will do in second scenario so hard to answer correctly.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • It's also worth mentioning that multiple `await`s will create multiple state machines (behind the scenes), while returning the `Task` directly will not. Might be a performance consideration. – Jon G Stødle Sep 27 '17 at 10:57
0

Option 1 is for CPU-bound work in the Background.

Option 2 is for asynchronous work, i.e. involving awaiting other Task-returning methods.

Haukinger
  • 10,420
  • 2
  • 15
  • 28
0

The async keyword will able you to use the await keyword in your code to await other Tasks (See async/await)

The Task.Run(...) will schedule your code to be executed by a Thread from the ThreadPool (See Task.Run Method)

Tiago Sousa
  • 953
  • 5
  • 14