Search code examples
c#asp.net.nethangfire

Should I use an async wrapper when calling the Hangfire BackgroundJob.Enqueue method?


Is it a good idea to put the Enqueue method in an async wrapper and have the controller call it that way?

Which is better and why?

Synchronously:

    public IActionResult AddLogs(List<Log> logs)
    {
        BackgroundJob.Enqueue(() => DM.AddLogsBackground(logs));
        return Ok();
    }

Async:

    public async Task<IActionResult> AddLogs(List<Log> logs)
    {
        await DM.AddLogs(logs);
        return Ok();
    }

    public async Task AddLogs(List<Log> logs)
    {
        BackgroundJob.Enqueue(() => AddLogsBackground(logs));
    }

The documentation says:

The Enqueue method does not call the target method immediately, it runs the following steps instead:

  1. Serialize a method information and all its arguments.
  2. Create a new background job based on the serialized information.
  3. Save background job to a persistent storage.
  4. Enqueue background job to its queue.

Solution

  • Which is better and why?

    As BackgroundJob.Enqueue is not awaited (nor awaitable) it will just be processed synchronously.

    So all the async syntax is useless and misleading here.

    Note that your DM.AddLogsBackground can be an async method. But as far as I know, the processing will still be synchronous on the background job server.