0

Below is the code snippet:

public async Task<ActionResult> GetProduct(int id)
        {
            /* 
             ---- some main thread logic...
             */

            Task.Run(() => {
                /* 
             ---- some background thread logic...
             */
            });

            return View();
        }

In the above code can I call Task.Run() logic without the use of async keyword in the action method? Is it mandatory to use async keyword with Task.Run()?

Please help me to get this clear.

Liam
  • 27,717
  • 28
  • 128
  • 190
swap
  • 85
  • 4
  • 2
    Depends on whether you want it to `await` or not – Liam Mar 11 '20 at 11:48
  • A big difference (**though certainly not the only difference**) is by adding `await` your task will run `return View` **after** your task returns, whereas without this `await` `return View` will (likely) return **before** your task returns. – Liam Mar 11 '20 at 11:49
  • @Liam, thanks for the help... Actually I don't want to use await. the intention is to use Task.Run() is that I want to run two threads, the main thread should not wait for the logic of Task.Run(). Task.Run() logic should run in the background. – swap Mar 11 '20 at 12:02
  • 1
    In which case, no, you don't want to use `await`. See [Simplest way to do a fire and forget method in c# 4.0](https://stackoverflow.com/questions/5613951/simplest-way-to-do-a-fire-and-forget-method-in-c-sharp-4-0) – Liam Mar 11 '20 at 13:41

1 Answers1

3

No, it's not mandatory.

You use the async keyword when you want to use await within a method.

Sean
  • 60,939
  • 11
  • 97
  • 136