private static void RunProcess(IBackgroundProcess process, BackgroundProcessContext context)
        {
            // Long-running tasks are based on custom threads (not threadpool ones) as in
            // .NET Framework 4.5, so we can try to set custom thread name to simplify the
            // debugging experience.
            TrySetThreadName(process.ToString());

            // LogProvider.GetLogger does not throw any exception, that is why we are not
            // using the `try` statement here. It does not return `null` value as well.
            var logger = LogProvider.GetLogger(process.GetProcessType());

            logger.Debug($"Background process '{process}' started.");

            try
            {
                process.Execute(context);
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException && context.IsShutdownRequested)
                {
                    // Graceful shutdown
                    logger.Trace($"Background process '{process}' was stopped due to a shutdown request.");
                }
                else
                {
                    logger.FatalException(
                        $"Fatal error occurred during execution of '{process}' process. It will be stopped. See the exception for details.",
                        ex);
                }
            }

            logger.Debug($"Background process '{process}' stopped.");
        }
Esempio n. 2
0
 private async Task RunProcess(IBackgroundProcess process)
 {
     try
     {
         while (_isStart && !_backgroundProcessContext.IsShutdownRequested)
         {
             try
             {
                 await process.Execute(_backgroundProcessContext); //内部控制异常
             }
             catch (OperationCanceledException ex)
             {
                 _logger.LogError(ex, "redis任务取消");
             }
             catch (RedisException ex)
             {
                 _logger.LogError(ex, "redis错误");
                 await TaskEx.DelayNoException(TimeSpan.FromSeconds(10), _backgroundProcessContext.CancellationToken);
             }
             catch (Exception ex)
             {
                 string errorMsg = $"执行任务{process.GetType().FullName}异常";
                 _logger.LogError(ex, errorMsg);
             }
         }
     }
     catch (Exception)
     {
     }
 }
Esempio n. 3
0
 public MainWindow(IMainWindowViewModel viewModel, IBackgroundProcess background)
 {
     InitializeComponent();
     DataContext = viewModel;
     _background = background;
     _background.Start();
 }
Esempio n. 4
0
 public SingleInstanceProcess(IDistributedLockService lockService, T innerProcess)
 {
     _lockService  = lockService;
     _innerProcess = innerProcess;
     ProcessName   = innerProcess.ProcessName;
     ProcessId     = innerProcess.ProcessId;
 }
Esempio n. 5
0
        public Task AddProcess(IBackgroundProcess backgroundProcess, string name)
        {
            _logger.LogInformation($"开启后台任务:{name}");
            _backgroundProcesses.Add(backgroundProcess);

            Task.Factory.StartNew(() => RunProcess(backgroundProcess), TaskCreationOptions.LongRunning);
            return(Task.CompletedTask);
        }
Esempio n. 6
0
        /// <summary>
        /// Adds the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        public Guid Add(IBackgroundProcess service)
        {
            var id = Process.Add(service);

            _serivceIds.Add(id);

            return(id);
        }
 public InfiniteLoopProcess([NotNull] IBackgroundProcess innerProcess)
 {
     if (innerProcess == null)
     {
         throw new ArgumentNullException(nameof(innerProcess));
     }
     InnerProcess = innerProcess;
 }
Esempio n. 8
0
        public AutomaticRetryProcess(IBackgroundProcess innerProcess)
        {
            _innerProcess = innerProcess ?? throw new ArgumentNullException(nameof(innerProcess));

            MaxRetryAttempts = DefaultMaxRetryAttempts;
            MaxAttemptDelay  = DefaultMaxAttemptDelay;
            DelayCallback    = GetBackOffMultiplier;
        }
        public BackgroundProcessWrapper(IBackgroundProcess process)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            _process = process;
        }
Esempio n. 10
0
        public static ITaskSource Wrap(this IBackgroundProcess process)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            return(new BackgroundProcessWrapper(process));
        }
Esempio n. 11
0
        public static IBackgroundProcess Loop(this IBackgroundProcess process)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            return(new InfiniteLoopProcess(new AutomaticRetryProcess(process)));
        }
Esempio n. 12
0
        private void launch(IBackgroundProcess process)
        {
            Logger.Info(string.Format("Run process={0}.", process.GetType().FullName));

            try
            {
                new Task(process.Start).Start();
            }
            catch(Exception ex)
            {
                Logger.Error(string.Format("Executing process={0}.", process.GetType().FullName), ex);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Adds the specified service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <returns></returns>
        public static Guid Add(IBackgroundProcess service)
        {
            Guid id;
            var  newService = new ProcessItem(service);

            do
            {
                id = Guid.NewGuid();
            }while (!_services.TryAdd(id, newService));

            newService.Start();

            return(id);
        }
Esempio n. 14
0
        public AutomaticRetryProcess([NotNull] IBackgroundProcess innerProcess)
        {
            if (innerProcess == null)
            {
                throw new ArgumentNullException(nameof(innerProcess));
            }

            InnerProcess = innerProcess;
            _logger      = LogProvider.GetLogger($"Hangfire.Async.Server.{innerProcess}");

            MaxRetryAttempts = DefaultMaxRetryAttempts;
            MaxAttemptDelay  = DefaultMaxAttemptDelay;
            DelayCallback    = GetBackOffMultiplier;
        }
        public static void Execute(this IBackgroundProcess process, BackgroundProcessContext context)
        {
            if (!(process is IBackgroundProcess))
            {
                throw new ArgumentOutOfRangeException(nameof(process), "Long-running process must be of type IServerComponent or IBackgroundProcess.");
            }

            var backgroundProcess = process as IBackgroundProcess;

            if (backgroundProcess != null)
            {
                backgroundProcess.Execute(context);
            }
        }
Esempio n. 16
0
        public BackgroundProcessDispatcherBuilder(
            [NotNull] IBackgroundProcess process,
            [NotNull] Func <ThreadStart, IEnumerable <Thread> > threadFactory)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }
            if (threadFactory == null)
            {
                throw new ArgumentNullException(nameof(threadFactory));
            }

            _process       = process;
            _threadFactory = threadFactory;
        }
        public static Type GetProcessType([NotNull] this IBackgroundProcess process)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            var nextProcess = process;

            while (nextProcess is IBackgroundProcessWrapper)
            {
                nextProcess = ((IBackgroundProcessWrapper)nextProcess).InnerProcess;
            }

            return(nextProcess.GetType());
        }
        public static Task CreateTask([NotNull] this IBackgroundProcess process, BackgroundProcessContext context)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            if (!(process is IBackgroundProcess))
            {
                throw new ArgumentOutOfRangeException(nameof(process), "Long-running process must be of type IServerComponent or IBackgroundProcess.");
            }

            return(Task.Factory.StartNew(
                       () => RunProcess(process, context),
                       TaskCreationOptions.LongRunning));
        }
        public static IBackgroundProcessDispatcherBuilder UseBackgroundPool(
            [NotNull] this IBackgroundProcess process,
            [NotNull] Func <string, ThreadStart, IEnumerable <Thread> > threadFactory)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }
            if (threadFactory == null)
            {
                throw new ArgumentNullException(nameof(threadFactory));
            }

            return(new BackgroundProcessDispatcherBuilder(
                       process,
                       threadStart => threadFactory(process.GetType().Name, threadStart)));
        }
Esempio n. 20
0
        public static IBackgroundProcessDispatcherBuilder UseBackgroundPool(
            [NotNull] this IBackgroundProcess process,
            int threadCount)
        {
            if (process == null)
            {
                throw new ArgumentNullException(nameof(process));
            }
            if (threadCount <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(threadCount));
            }

            return(UseBackgroundPool(
                       process,
                       (threadName, threadStart) => DefaultThreadFactory(threadCount, threadName, threadStart)));
        }
Esempio n. 21
0
        private void Execute(IRespondWithNoResultSuccessOrError <ErrorOutput> presenter)
        {
            var processStartInfo = _processPipeLineTask.CommandToExecute();

            try
            {
                _process = _processFactory.CreateBackgroundProcess(processStartInfo);

                _process.Start();

                var errorTask = _process.ReadStdErrToEndAsync();

                if (!errorTask.Wait(500))
                {
                    // was there error data to fetch?
                    presenter.Respond();
                    return;
                }

                var error = errorTask.Result;
                if (HasError(error))
                {
                    var errorOutput     = new ErrorOutput();
                    var trimedArugments = processStartInfo.Arguments.Substring(3);
                    errorOutput.AddError($"Failed to execute {trimedArugments}");
                    errorOutput.AddError(error);
                    presenter.Respond(errorOutput);
                    return;
                }

                presenter.Respond();
            }
            catch (Exception e)
            {
                throw new Exception($"Failed to execute [{processStartInfo.FileName}] with [{processStartInfo.Arguments}]", e);
            }
        }
Esempio n. 22
0
 public InfiniteLoopProcess(IBackgroundProcess innerProcess)
 {
     InnerProcess = innerProcess ?? throw new ArgumentNullException(nameof(innerProcess));
 }
 public static IBackgroundProcessDispatcherBuilder UseBackgroundPool(
     [NotNull] this IBackgroundProcess process,
     int threadCount)
 {
     return(UseBackgroundPool(process, threadCount, null));
 }
 public static IBackgroundProcessDispatcherBuilder UseBackgroundPool(
     [NotNull] this IBackgroundProcess process)
 {
     return(UseBackgroundPool(process, Environment.ProcessorCount));
 }
 public void Start(IBackgroundProcess additionalProcess) =>
 _instance.Start(additionalProcess.AsArray());
Esempio n. 26
0
 internal ProcessItem(IBackgroundProcess serivce)
 {
     IsServiceStopped = true;
     _serivce         = serivce;
 }
Esempio n. 27
0
#pragma warning disable 618
        private static IBackgroundProcess WrapProcess(IBackgroundProcess process)
#pragma warning restore 618
        {
            return(new InfiniteLoopProcess(new AutomaticRetryProcess(process)));
        }
Esempio n. 28
0
 private static IBackgroundProcess WrapProcess(IBackgroundProcess process)
 {
     return(new InfiniteLoopProcess(new AutomaticRetryProcess(process)));
 }
Esempio n. 29
0
 public static void Execute(this IBackgroundProcess process, BackgroundProcessContext context)
 {
     process.Execute(context);
 }
Esempio n. 30
0
 /// <summary>
 /// Adds the specified service.
 /// </summary>
 /// <param name="service">The service.</param>
 /// <returns></returns>
 public async Task <Guid> AddAsync(IBackgroundProcess service)
 {
     return(await Task.Run(() => Add(service)));
 }