We left Russia. We are against aggression and war with Ukraine. It is a tragedy for our nations, it is a nightmare

Multiple Jobs are Enqueuing due to race condition

Hi All,

I have a problem where I’m watching the filesystem for changes, which when invoked will queue up a job. My goal is to only allow one of these jobs to be scheduled via this filesystem change mechanism, while it can be called as much as needed via API.

I’m using a piece of code, which works for everything else, to check if a job is already enqueued. The problem I’m running into is I have multiple tasks running at the same time and checking if a job is enqueued or not, however, the race condition comes in as they are ns between each other and hence, I’m getting tons of jobs scheduled.

Does anyone have any ideas what I can do to alleviate this? I tried locking but no success, just timeouts.

/// <summary>
    /// Checks if this same invocation is already enqueued
    /// </summary>
    /// <param name="methodName">Method name that was enqueued</param>
    /// <param name="className">Class name the method resides on</param>
    /// <param name="args">object[] of arguments in the order they are passed to enqueued job</param>
    /// <param name="queue">Queue to check against. Defaults to "default"</param>
    /// <returns></returns>
    public static bool HasAlreadyEnqueuedTask(string className, string methodName, object[] args, string queue = DefaultQueue)
    {
        var enqueuedJobs =  JobStorage.Current.GetMonitoringApi().EnqueuedJobs(queue, 0, int.MaxValue);
        return enqueuedJobs.Any(j => j.Value.InEnqueuedState &&
                                     j.Value.Job.Method.DeclaringType != null && j.Value.Job.Args.SequenceEqual(args) &&
                                     j.Value.Job.Method.Name.Equals(methodName) &&
                                     j.Value.Job.Method.DeclaringType.Name.Equals(className));
    }