Search code examples
c#concurrencyhangfire

Control Hangfire concurrency by a parameter


I have a hangfire job being enqueued the following way:

BackgroundJob.Enqueue(() => AnalyzeRequest(request)); 

The request object contains a userName string type field. I would like to allow requests to get analyzed in parallel as long as they have different values in the userName field, but requests that belong to the same user should be analyzed one after the other. Since i'd like to keep the concurrency for different user requests, I wouldn't want to use the DisableConcurrentExecution attribute. Ideally I would want to do something like this:

[DisableConcurrentExecution(request => request.userName)]

Is there any built-in way to achieve this?

Thanks


Solution

  • I'm pretty sure hangfire can't group them by username or parameter, let along sequentially execute them (which is possible but looks very bad - you should create job inside job on finish, but this can fail and comes with a bunch of hacky code).

    What I recommend you to do - is manage this inside your AnalyzeRequest() method. For example, you can create shared Dictionary of username and their respective lock objects. And on execution invoke Monitor.TryEnter on this object. If enter is succeeded - proceed further, otherwise - gracefully abandon job.

    Yes, it will create "empty" job invokations, but hangfire can handle this empty calls pretty good.