Search code examples
c#asp.netasp.net-core-2.0hangfire

How to use await with hangfire background job?


I am using hangfire with .net core 2.1. Now the issue is I am using httpclient for making multiple web requests and hangfire doesn't support async methods I think. So the response return before all the web requests are completed. I have commented this line:

_backgroundJob.Enqueue(() => EnqueueMyMethodCallBack(email)); 

and used this line:

await EnqueueMyMethodCallBack(email)

then it was working fine. So is there any way I can await _backgroundJob.Enqueue ? Also I have found this article https://www.hangfire.io/blog/2016/07/16/hangfire-1.6.0.html where it was written that async methods are now supported but I still can't use them.

And the EnqueueMyMethodCallBack method:

public async Task<bool> EnqueueMyMethodCallBack(string email)
{
  var response = await _userRepo.GetUser(email);
  if(response == null)
    return false;
  var template = await _template.GetTemplate();
  await _email.Send(template, email);
  return true; 
}

Any help?


Solution

  • Enqueue just adds the job to the queue. The job is executed at a later time, in a different context, even on a potentially different machine (hangfire supports multiple worker machines). It returns the job id so you can query for it later (check status/etc.).

    If you want your job to run in that context, call it directly.

    So, if the request needs to return something from that job, you don't need a job. There's no point in scheduling a job and awaiting it to finish so you can return something.