How to invoke async methods in Hangfire?
Asked Answered
S

1

50

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());
    }
}
Shenika answered 29/3, 2017 at 20:2 Comment(0)
E
112

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.

Escape answered 29/3, 2017 at 21:5 Comment(4)
Good answer (up-voted you). One thing to point out from their documentation "Real asynchrony may come in Hangfire 2.0 only, and it requires a lot of breaking changes to the existing types." hangfire.io/blog/2016/07/16/hangfire-1.6.0.htmlPlunk
Found it after read a little further down. it was in the same blog article i linked to in the answer. thanks.Escape
Same for recurring tasks?Heshum
Never use ConfigureAwait(bool) with _downloader.DownloadAsync(files) or you will keep inviting problems.Fideicommissum

© 2022 - 2024 — McMap. All rights reserved.