Get the worker process id


it is possible to get the worker process id (the number should be between 1 to WorkerCount or something unique) when a background job is running?
I need to make some operations idempotent.
Now i use System.Diagnostics.Process.GetCurrentProcess().Id but don’t know if multiple workers can have the same id.

Someone has any idea?

Thank you

Multiple workers sure can have the same process id, since they’re threads running inside the same process.

To get a unique worker id, you may use something like:

public void JobMethod(PerformContext context)
    string workerId = null;

    var state = context.Connection.GetStateData(context.BackgroundJob.Id);
    if (state != null && state.Name == ProcessingState.StateName && state.Data.ContainsKey("WorkerId"))
        // valid job state, get worker id
        workerId = state.Data["WorkerId"];

    // ...

I’m not sure why you may need it though, because another instance of the same job may simultaneously run on another worker. On the contrary, any worker may execute only one job at a time, so it is impossible for two running jobs to have the same worker id.

Thank you, is working great!
The idea is that i use a background job to aggregate some data (per month) and store that in DB.
To make the operation idempotent and because multiple jobs can run in the same time, i store an aggregated row per workerId. After that another job is summing all those aggregated rows per worker.

You should consider what would happen to your aggregated data when the job is requeued (for whatever reason). Next run will most likely occur on a different worker, so you’d have your aggregated data stored twice.

Also if you have many jobs concurrently aggregating data subsets, there might be a case when the same worker executes several jobs in sequence, and them all will use the same worker id to store aggregated data under.

You might probably want to use job id instead of worker id. It is also unique, and would remain the same if the job is requeued.