How to catch return object from BackgroundJob.Enqueue()?

If the method passed to Enqueue() returns an object, how do I catch this object:
I tried:

BackgroundJob.Enqueue ( () => var object =  myMethod(id)); 

and

var object; 
BackgroundJob.Enqueue ( () => object =  myMethod(id)); 

But an errors were thrown.

What do you need to do with the returned object?

I’ll need to pass this object to the corresponding View. For example, I’d like to queue the job of finding an object in the database:

Student student = db.Students.Find(id) 

This returns a student object whether null or not, how do I enqueue such job?

BackgroundJob.Enqueue(() => Student student = db.Students.Find(id); //This gives me an error
......................................................
 Student student; 
 BackgroundJob.Enqueue(() => student = db.Students.Find(id); //This also gives me an error

You shouldn’t assume that you’ll be able to use the result of the background job in the scope of the calling method. Perhaps an asynchronous operation will be more suited to your needs - you can await it and use the results after that. Also, you shouldn’t rely on Hangfire’s result, since that could be cleaned up during database maintenance. Finally, returning entities in a background job is not something you’ll want to do, since you’ll only get the serialized entity without its relationships and so on.

That being said, there are ways to access the result of the background operation. This article explains the two basic mechanisms - polling and pushing updates. Basically, in the simplest case, you need an ajax call every few seconds polling a server method to ask it about the result. And to get the results of a background job, you can use the MonitoringApi:

var api = JobStorage.Current.GetMonitoringApi();
var jobDto = api.SucceededJobs(0, int.MaxValue).FirstOrDefault(job => job.Key == /*your key*/).Value;
if (jobDto != null)
{
    var result = jobDto.Result;
   /* Do something with result */
}

It’s not overly effective, but should work. Still, I’d suggest that you either reconsider your requirements or provide us with more context (e.g. the complete method that will schedule the background task and the method that will consume the result).

2 Likes