Home > Back-end >  C# .NET - detect if code is running as a hangfire job
C# .NET - detect if code is running as a hangfire job

Time:01-31

Is it possible to detect if code is running as a hangfire job in C#? Thank you

I would expect that some global system variable exists and indicates code is running as a part of hangfire job.

CodePudding user response:

I would expect that some global system variable exists and indicates code is running as a part of hangfire job.

I would be curious about your usecase. Having code depending explicitly on the execution context is more difficult to maintain and test in my opinion. Is it because your code depends on HttpContext, which is not available when running the task with Hangfire ?

Anyway, you could achieve what you want with AsyncLocal and Hangfire ServerFilters

public static class HangfireTaskMonitor
{
    public static AsyncLocal<bool> IsRunningInBackground { get; } = new AsyncLocal<bool>();
}

public class ContextTrackedAttribute : JobFilterAttribute, IServerFilter
{
    public void OnPerforming(PerformingContext filterContext)
    {
      HangfireTaskMonitor.IsRunningInBackground.Value = true;
    }

    public void OnPerformed(PerformedContext filterContext)
    {
      HangfireTaskMonitor.IsRunningInBackground.Value = false;
    }
}

Then put the [ContextTracked] attribute on your job method and test HangfireTaskMonitor.IsRunningInBackground.Value whenever you want.

The idea is somewhat simplified for clarity. For a more decoupled solution, I would have the HangfireTaskMonitor being injected as a singleton instead of a static class ; have the filter be a simple filter declared upon Hangfire configuration, instead of being an attribute.

CodePudding user response:

Yes, it's possible to detect if code is running as a Hangfire job in C#. One way to do this is to use the JobContext.Current property from the Hangfire.Core namespace. This property returns a IJobCancellationToken instance that represents the current job context, or null if the code is not running within a Hangfire job.

Here's an example of how to use the JobContext.Current property to check if code is running as a Hangfire job:

using Hangfire.Core;

...

if (JobContext.Current != null) {
  Console.WriteLine("This code is running as a Hangfire job.");
} else {
  Console.WriteLine("This code is not running as a Hangfire job.");
}

You can also check if the current thread has a JobCancellationToken associated with it using the JobCancellationToken.Current property, as shown below:

using Hangfire.Core;

...

if (JobCancellationToken.Current != null) {
  Console.WriteLine("This code is running as a Hangfire job.");
} else {
  Console.WriteLine("This code is not running as a Hangfire job.");
}
  • Related