In my case, i have many methods running in parallel, but i can't run the same method more than once.
Using a solution from this topic, I just edited the query. If was already one method in the processing list with the same name of the actual method, the execution is cancelled.
I believe that resolve a lot of cases.
- Create this class:
using Hangfire.Client;
using Hangfire.Common;
using Hangfire.Server;
using Hangfire;
public class PreventConcurrentExecutionJobFilter : JobFilterAttribute, IClientFilter, IServerFilter
{
public void OnCreating(CreatingContext filterContext)
{
var jobs = JobStorage.Current.GetMonitoringApi().ProcessingJobs(0, 100);
var methodAlreadyProcessing = jobs.Any(x => x.Value.Job.Method.Name == filterContext.Job.Method.Name);
if (methodAlreadyProcessing)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss} - Job {filterContext.Job.Method.Name} cancelled why was already exists in processing list!");
filterContext.Canceled = true;
}
}
public void OnPerformed(PerformedContext filterContext) { }
void IClientFilter.OnCreated(CreatedContext filterContext) { }
void IServerFilter.OnPerforming(PerformingContext filterContext) { }
}
- Put the Annotation in your method:
[PreventConcurrentExecutionJobFilter]
public async Task MyTopTask()
{
...
}