简体   繁体   中英

Use await for background threads or not?

I'm currently getting into the async/await keywords, and went through the following questions: When correctly use Task.Run and when just async-await and Async/Await vs Threads

However even the second link doesn't answer my question, which is when to simply use

Task.Run(...)

versus

await Task.Run(...)

Is it situational or is there something to be gained by using await (and thus returning to the caller)?

The code Task.Run(...) (in both examples) sends a delegate to the thread pool and returns a task that will contain the results of that delegate. These "results" can be an actual return value, or it can be an exception. You can use the returned task to detect when the results are available (ie, when the delegate has completed).

So, you should make use of the Task if any of the following are true:

  • You need to detect when the operation completed and respond in some way.
  • You need to know if the operation completed successfully.
  • You need to handle exceptions from the operation.
  • You need to do something with the return value of the operation.

If your calling code needs to do any of those, then use await :

await Task.Run(...);

With long-running background tasks, sometimes you want to do those (eg, detect exceptions), but you don't want to do it right away ; in this case, just save the Task and then await it at some other point in your application:

this.myBackgroundTask = Task.Run(...);

If you don't need any of the above, then you can do a "fire and forget", as such:

var _ = Task.Run(...); // or just "Task.Run(...);"

Note that true "fire and forget" applications are extremely rare . It's literally saying "run this code, but I don't care whether it completes, when it completes, or whether it was successful".

You can use Task.Run() when handling logic with fire and forget type, similar to invoking events if someone is subscribed to them. You can use this for logging, notifying, etc.

If you depend of the result or actions executed in your method, you need to use await Task.Run() as it pauses current execution until your task is finished.

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