How to invoke async methods in Hangfire?

Based on one of the examples on the repository on github

Just remove the Wait blocking call

_backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files));

The method knows now how to handle Func that returns Task

Hangfire 1.6.0 – Blog

The enqueueing logic is the same for sync and async methods. In early
betas there was a warning CS4014, but now you can remove all the
#pragma warning disable statements. It was implemented by using Expression<Func<Task>> parameter overloads.

BackgroundJob.Enqueue(() => HighlightAsync(snippet.Id));

Note:

That’s not a real asynchrony

Please consider this feature as a syntactic sugar. Background
processing hasn’t became asynchronous. Internally it was implemented
using the Task.Wait method, so workers don’t perform any processing,
while waiting for a task completion. Real asynchrony may come in
Hangfire 2.0 only, and it requires a lot of breaking changes to the
existing types.

Leave a Comment

tech