Esempio n. 1
0
        public async Task <StateContext> TestAsync(IWorkContext context)
        {
            Verify.IsNotNull(nameof(context), context);
            context = context.WithTag(_tag);

            var stateContext = new StateContext();

            context = context
                      .ToBuilder()
                      .Set(stateContext)
                      .Build();

            int isRunning = Interlocked.CompareExchange(ref _running, (int)RunStatus.Running, (int)RunStatus.Stopped);

            if (isRunning == (int)RunStatus.Running)
            {
                throw new InvalidOperationException("State plan is already running");
            }

            try
            {
                Interlocked.Exchange(ref _isSuccessful, 0);
                context.EventLog.Verbose(context, "Running state plan");

                stateContext.WorkItemIndex = 0;

                foreach (var item in StateItems)
                {
                    bool result = await item.Test(context);

                    Notify?.Invoke(new StateNotify(item, StateNotify.ActionTypes.Test, result));

                    context.CancellationToken.ThrowIfCancellationRequested();
                    context.EventLog.Verbose(context, $"Executed state plan 'Test' for item {item.Name} with {result} result");

                    if (!result)
                    {
                        return(stateContext);
                    }

                    stateContext.WorkItemIndex++;
                }

                Interlocked.Exchange(ref _isSuccessful, 1);
                stateContext.IsSuccessFul = true;

                context.EventLog.Verbose(context, "State plan completed successfully");
                return(stateContext);
            }
            finally
            {
                Interlocked.Exchange(ref _running, (int)RunStatus.Stopped);
                context.EventLog.Verbose(context, "State plan exited");
            }
        }