How to invoke async methods in Hangfire?

LP13 picture LP13 · Mar 29, 2017 · Viewed 17k times · Source

I have asp.net core API application and this is the first time i will be using HangFire.

In .Net Core application all my methods are async. Based on SO Post it's not good idea to use wait() while calling async method in hangfire.
Also as per the hangfire support issue in v1.6.0, async support was added. I am using version 1.6.12 but still i dont see async support.

How do i call async method from Enqueue. Currently i am using wait()

public class MyController : Controller
{
    private readonly Downloader _downlaoder;
    private readonly IBackgroundJobClient _backgroungJobClient;
    public MyController(Downloader downloader, IBackgroundJobClient backgroungJobClient)
    {
        _downlaoder = downloader;
        _backgroungJobClient = backgroungJobClient;
    }

    [HttpPost]
    public void Post([FromBody]IEnumerable<string> files)
    {
        _backgroungJobClient.Enqueue(() => _downloader.DownloadAsync(files).Wait());
    }
}

Answer

Nkosi picture Nkosi · Mar 29, 2017

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.