Nested Batches failing to be created

Hello,

I am currently running into issues attempting to create nested batches within our application. Looking around it appears that others have also ran into a similar issue: Error with Hangfire Nested Batches

I wanted to know if there was anything being worked on for this issue or if there were any ideas for avoiding the error entirely. Below you can find a code sample which reproduces the issue:

BatchJob.StartNew(primaryBatch =>
		{
			for (int i = 0; i < 10; i++)
			{
				var firstTaskId = primaryBatch.Enqueue(() => Console.WriteLine("Store Document Information"));
				var processIndividualPagesBatch = primaryBatch.AwaitJob(firstTaskId, pagesBatch =>
				{
					pagesBatch.Enqueue(() => Console.WriteLine("Process page 1"));
					pagesBatch.Enqueue(() => Console.WriteLine("Process page 2"));
					pagesBatch.Enqueue(() => Console.WriteLine("Process page 3"));
					pagesBatch.Enqueue(() => Console.WriteLine("Process page 4"));
				});

				// Error occurs because of this await batch call.
				primaryBatch.AwaitBatch(processIndividualPagesBatch, completeDoc =>
				{
					completeDoc.Enqueue(() => Console.WriteLine("Perform action based on results of page processing."));
				});
			}
		});

The issue with the above code is the AwaitBatch call. Without that within the batch there is no issue. Here is the full exception which I am receiving:

Hangfire.CreateBatchFailedException : An exception occurred while creating the batch. See the inner exception for 
details.
  ----> System.InvalidOperationException : Operation is not valid due to the current state of the object.
   at Hangfire.BatchJobClient.Create(Action`1 createAction, IBatchState state, String description)
   at NestedBatchReproduction.NestedBatches() in NestedBatchReproduction.cs:line 18
--InvalidOperationException
       at Hangfire.Batches.BatchContinuationsSupportAttribute.AddContinuation(ElectBatchStateContext context, BatchAwaitingState awaitingState)
   at Hangfire.Batches.BatchContinuationsSupportAttribute.OnStateElection(ElectBatchStateContext context)
   at Hangfire.Batches.States.BatchStateMachine.ApplyState(ApplyBatchStateContext context)
   at Hangfire.Batches.States.BatchStateMachine.ApplyBatchStates(ApplyBatchStateContext context, ICollection`1 batchedJobs)
   at Hangfire.Batches.States.BatchStateMachine.RunStateAction(ApplyBatchStateContext context)
   at Hangfire.Batches.States.BatchStateMachine.ApplyState(ApplyBatchStateContext context)
   at Hangfire.Batches.Client.BatchFactory.Create(BatchCreateContext context)
   at Hangfire.BatchJobClient.Create(Action`1 createAction, IBatchState state, String description)

Hangfire.Pro 2.1.0 released with full continuations support in nested batches, please see https://www.hangfire.io/blog/2017/09/01/hangfire.pro-2.1.0.html.

Thanks! Confirmed that my issue was resolved here. Really appreciate it.

1 Like