/// <summary> /// Gets a saga instance with a specific correlation id if it is in a specific state. /// If the instance is not yet in that state, waits for a certain amount of time. /// Returns null if the instance can not be found or is not in the desired state. /// </summary> /// <param name="correlationId"></param> /// <param name="state"></param> /// <returns></returns> private async Task <ISagaInstance <LifeState> > FindSagaInstance(Guid correlationId, State state) { ISagaInstance <LifeState> sagaInstance; if (state == _machine.Final) { // Match doesn't seem to work with the Final state, check that by name var startTime = DateTime.Now; while (true) { Thread.Sleep(100); sagaInstance = _sagaHarness.Sagas.FirstOrDefault(instance => instance.Saga.CurrentState == "Final"); if (sagaInstance != null) { break; } if (DateTime.Now - startTime > _testTimeout) { break; } } ; } else { // Wait till the saga instance transitions to the expected state - or fail after a timeout. IList <Guid> matchingSagaIds = await _sagaHarness.Match( x => x.CorrelationId == correlationId && x.CurrentState == state.Name, _testTimeout); if (matchingSagaIds.Count == 0) { return(null); } sagaInstance = _sagaHarness.Sagas.FirstOrDefault(i => i.Saga.CorrelationId == correlationId); } return(sagaInstance); }