1

Say I want to run code in the background in a Web API controller that will not delay the user response. In addition, making the code run in the background does not mean I don't care about it's performance and the amount of work it creates for the server. So, in order to make it efficient I would like to use async & await for maximum use of CPU time.

There are several approaches I've tried but don't quite get the difference between them, if there is such:

1.

Task.Factory.StartNew(() => 
SomeAsyncFunction(param), TaskCreationOptions.PreferFairness);

In this case I created a new Task calls an async function that also uses await inside. I am not using await outside since I don't want the code to wait. Note that unlike when writing this code in a regular function, I don't get the "Consider adding the 'await' operator" warning.

The code does run in the background, but are the async & await traits used?

2.

Task.Factory.StartNew(async () => 
await SomeAsyncFunction(param), TaskCreationOptions.PreferFairness);

Almost the same case but this time using an async anonymous function and using the await operator inside it. Is it different from the first case at all in terms of async & await traits?

I've seen a quite similar question here but I'm more interested in understanding how it works than getting a complicated ready-made solution for the problem

Thanks!

Community
  • 1
  • 1
omerko
  • 19
  • 1
  • 1. Use `Task.Run` instead of `Task.Factory.StartNew`. 2. Both calls would act the same from the caller's perspective but the seconds adds a slight redundant overhead – i3arnon Jan 20 '15 at 10:00
  • http://stackoverflow.com/a/23383587/885318 – i3arnon Jan 20 '15 at 10:03
  • "The same" means using the async & await traits? why is Task.Run better? – omerko Jan 20 '15 at 10:06
  • The same means the functionality is the same. The first option doesn't use `async-await` in the lambda itself, it just returns a task. – i3arnon Jan 20 '15 at 10:09

0 Answers0