CancellationToken in a different thread

Goodmorning,
this is the first time I write in this forum.
My name is Ciro.
I’m using Hangfire for a production web application project.

My question is about safety of checking cancellationToken status in another thread respect of the main thread of the job .

The code I want to execute is the following:

public void exec(List<object> parameters = null, bool useCancellationToken = false, IJobCancellationToken cancellationToken = null) {

    //cancellation job logic
    if (useCancellationToken && cancellationToken != null && cancellationToken != JobCancellationToken.Null) {

        Task.Run(() => {
            for (var i = 0; i < Int32.MaxValue; i++) {
                cancellationToken.ThrowIfCancellationRequested();
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
        });
    }
    
    //job execution
    job_implementation(parameters);
    
}

Thank you all

Best regards
Ciro Corvino

Cancellation tokens are generally thread safe by design so passing them between threads and checking them should not be a problem.

I do not think JobCansellationToken is any different.

1 Like

Thank you DMartensson.

Maybe, it is another question… but I’d like also to know if launching several threads in an Hangfire job it is a “safe” practice or it may lead to problems, or may reduce web application performances, etc…

We do not use hangfire as a live backend to webpages like that but for fire and forget jobs and schedule jobs.

Search the forum and if you do not find a good question, ask it as a new question so you get a relevant title, that way those that might know have an easier time finding the question and other with the same question can find you question :smiley:

In fact, the method reported in my OP is a common interface for “fire and forget” jobs and “recurring”… Anyway I take your suggest and ask a new question. Thank you again for your support (y)