HangfireIO/Hangfire · error · ArgumentException

All the threads should be non-null and in the ThreadState.Un

Error message

All the threads should be non-null and in the ThreadState.Unstarted state.

What it means

Thrown by the BackgroundTaskScheduler constructor when the threadFactory returns at least one thread that is null or not in the ThreadState.Unstarted state. The scheduler starts each thread itself (line 135) and records their ManagedThreadIds, so pre-started or null threads break ownership and inline-execution tracking.

Source

Thrown at src/Hangfire.Core/Processing/BackgroundTaskScheduler.cs:130

            _semaphore = new Semaphore(0, Int32.MaxValue);

            // Stopped event should always be the first in this array, see the DispatchLoop method.
            _waitHandles = new WaitHandle[] { _stopped, _semaphore };

#if !NETSTANDARD1_3
            AppDomainUnloadMonitor.EnsureInitialized();
#endif

            _threads = threadFactory(DispatchLoop)?.ToArray();

            if (_threads == null || _threads.Length == 0)
            {
                throw new ArgumentException("At least one non-started thread should be created.", nameof(threadFactory));
            }

            if (_threads.Any(static thread => thread == null || (thread.ThreadState & ThreadState.Unstarted) == 0))
            {
                throw new ArgumentException("All the threads should be non-null and in the ThreadState.Unstarted state.", nameof(threadFactory));
            }

            foreach (var thread in _threads)
            {
                thread.Start();
            }

            _ourThreadIds = new HashSet<int>(_threads.Select(static x => x.ManagedThreadId));
        }

        /// <inheritdoc />
        public override int MaximumConcurrencyLevel => _threads.Length;

        /// <summary>Signals all the threads to be stopped and releases all the unmanaged resources.
        /// This method should be called only when you are uninterested on the corresponding tasks,
        /// i.e. during AppDomain unloads, process shutdowns, etc.</summary>
        public void Dispose()
        {

View on GitHub (pinned to c236dd0f93)

Solutions

  1. Return only freshly-created, unstarted Thread objects (new Thread(start)) and never call Start() in the factory.
  2. Filter nulls and ensure the collection stays non-empty afterwards.
  3. Mirror BackgroundTaskScheduler.DefaultThreadFactory which sets Name/IsBackground but does not start.

Example fix

// before
Func<ThreadStart, IEnumerable<Thread>> factory = start => {
    var t = new Thread(start); t.Start(); return new[] { t }; // started -> throws
};

// after
Func<ThreadStart, IEnumerable<Thread>> factory = start =>
    new[] { new Thread(start) { IsBackground = true, Name = "BTS Worker" } }; // unstarted
Defensive patterns

Strategy: validation

Validate before calling

Func<ThreadStart, IEnumerable<Thread>> factory = start =>
    Enumerable.Range(0, count)
              .Select(i => new Thread(start) { IsBackground = true, Name = $"Worker #{i}" })
              .Where(t => t != null); // never start, never return started threads

Type guard

static bool IsUnstarted(Thread t) =>
    t != null && (t.ThreadState & System.Threading.ThreadState.Unstarted) != 0;

Try / catch

try { var s = new BackgroundTaskScheduler(factory, handler); }
catch (ArgumentException ex) when (ex.ParamName == nameof(threadFactory))
{ /* rebuild factory without calling Start() */ }

Prevention

When it happens

Trigger: A threadFactory that calls thread.Start() before returning, returns a previously-started Thread, or includes a null element in the collection.

Common situations: Reusing a cached Thread that was already started; a factory that eagerly starts threads 'to be safe'; a conditional that inserts null for a skipped slot; copying a factory pattern but adding an inadvertent Start().

Related errors


AI-assisted analysis of HangfireIO/Hangfire@c236dd0f93 (2026-08-13). Data as JSON: /api/errors/4f9b17d76639e534. Report an issue: GitHub.