When using QueueBackgroundWorkItem, is there any difference in the below two ways of calling a method that performs async operations like api calls?
HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
{
var result = await LongRunningMethodAsync();
});
Or the following:
HostingEnvironment.QueueBackgroundWorkItem(cancellationToken => LongRunningMethodAsync());
I’m aware of the detailed answers in Why use async with QueueBackgroundWorkItem? But they appear to focus on whether calling the Async vs Sync version of LongRunningMethod are better, and are not clear as to whether the above would make any difference.
I currently use the second method through-out my web application and can see that my async operations do in fact appear to run async.
2
Answers
From the docs:
So the difference would be that the first one will result in the scheduled task being monitored by the ASP.NET until completion of
LongRunningMethodAsync
while the second one will fire theLongRunningMethodAsync
and from the ASP.NET perspective the work item will be considered completed (see the source code bothQueueBackgroundWorkItem
will actually create a task and schedule it on custom scheduler –BackgroundWorkScheduler
).So I think the first one is preferable in this case.
P.S.
Do not forget to pass
cancellationToken
toLongRunningMethodAsync
.There’s no difference in this case, as I explain on my blog. They’re both calling the asynchronous overload, and they both run asynchronously.
In a more broad perspective, I discourage
QueueBackgroundWorkItem
in general because there’s no guarantee thatLongRunningMethodAsync
will complete. If you want a reliable solution, you need to use a durable queue with a background worker, also explained on my blog.