How to call asynchronous methods in Hangfire?

I have the main asp.net API application and am using HangFire for the first time.

In .Net Core, all my methods are asynchronous. Based on the SO Post, you should not use wait() when calling the asynchronous method in hangfire.
Also in accordance with the hangfire support issue in v1.6.0, asynchronous support has been added. I am using version 1.6.12, but still I do not see asynchronous support.

How do I call an asynchronous method from Enqueue . I am currently 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()); } } 
+13
source share
1 answer

Based on one example on github repository

Just delete Wait call blocking

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

Now the method knows how to handle Func, which returns Task

Hangfire 1.6.0 - Blog

The queuing logic is the same for synchronization and asynchrony methods. There was warning CS4014 in early beta versions, but now you can remove all #pragma warning disable statements. This was implemented using Expression<Func<Task>> parameter overloads.

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

Remarks:

This is not true asynchrony.

Please consider this function as syntactic sugar. Background processing did not become asynchronous. Internally, this was implemented using the Task.Wait method, so workers do not do any processing while waiting for the task to complete. True asynchrony can only appear in Hangfire 2.0, and it requires many major changes to existing types.

+35
source

Source: https://habr.com/ru/post/1266087/


All Articles