0

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.

Gary
  • 742
  • 8
  • 20

2 Answers2

1

is there any difference in the below two ways of calling a method that performs async operations like api calls?

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 that LongRunningMethodAsync will complete. If you want a reliable solution, you need to use a durable queue with a background worker, also explained on my blog.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 1
    Thanks for that definitive answer Stephen. I understand the risks of QueueBackgroundWorkItem from your detailed articles on the subject. Was just looking for clarity on how .NET would actually handle these two routes. – Gary Apr 04 '23 at 14:05
0

From the docs:

Differs from a normal ThreadPool work item in that ASP.NET can keep track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing.

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 the LongRunningMethodAsync and from the ASP.NET perspective the work item will be considered completed (see the source code both QueueBackgroundWorkItem 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 to LongRunningMethodAsync.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Ok, so no real effect on performance/scalability/blocking of threads. This would be more to do with ensuring ASP.NET tries to shut them down gracefully? – Gary Apr 03 '23 at 09:57
  • @Gary based on the quick look at the `BackgroundWorkScheduler` - yes. – Guru Stron Apr 03 '23 at 10:01