Fire and Forget and Awaiting in Async/Await: Differences and usage scenarios
The following code shows the different ways of calling the Callee
method and their behavioral differences.
Call #1: Fire and Forget (Simple)
Callee
The method is called asynchronously and does not block the caller.
Call #2: Awaiting task (delay)
TheCallee
method uses the await
keyword and the caller waits for it to complete. Since the Callee
method contains a 1000ms delay, it will take more than a second for the caller.
Call #3 & #5: Task.Run(Fire and Forget)
Task.Run
Submits the Callee
method to the thread pool for execution. Since await
is not used, both calls are Fire and Forget and do not block the caller.
Call #4 & #6: Task.Run(Await task)
Similar to #3 and #5, but Task.Run
uses await
internally. This makes them equivalent to #2, the caller will wait for the task to complete.
The difference between #3 and #5
While #3 and #5 both use Task.Run
, there are subtle differences. In #3, Callee
is called directly to create a new task on the thread pool. In #5, Callee
is wrapped in an async lambda expression, which creates a new task with its own state machine. However, since both missions are Fire and Forget, the difference isn't significant in this case.
Notes on Service Fabric
After migrating to Service Fabric, HostingEnvironment.QueueBackgroundWorkItem
is no longer supported. While it is possible to use Task.Run
as an alternative, it is better to use a separate background process and communicate with it via a queue. This ensures isolation between front-end and back-end services, preventing performance issues or deadlocks.
The above is the detailed content of Fire and Forget vs. Awaiting in Async/Await: What's the Difference and When Should You Use Each?. For more information, please follow other related articles on the PHP Chinese website!