skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search