Example #1
0
        /// <summary>
        /// Starts a new thread which executes a one-time action with a custom exception handler.
        /// </summary>
        /// <param name="taskMethod">An Action representing the method to perform.</param>
        /// <param name="exceptionHandler">IManagedTaskExceptionHandler used to handle exceptions for the new task</param>
        private void StartNewTask(Action <CancellationToken> taskMethod, IManagedTaskExceptionHandler exceptionHandler)
        {
            if (taskMethod == null)
            {
                throw new ArgumentNullException(nameof(taskMethod));
            }

            _tasks.Add(
                Task.Factory.StartNew(
                    () =>
            {
                try
                {
                    taskMethod(_cancellationTokenSource.Token);
                }
                catch (Exception ex)
                {
                    exceptionHandler?.HandleException(ex);
                }
            }
                    )
                );
        }
Example #2
0
        /// <summary>
        /// Starts a new thread which executes a recurring action with a custom exception handler.
        /// </summary>
        /// <param name="taskMethod">An Action representing the method to perform.</param>
        /// <param name="delay">a System.TimeSpan indicating how long to wait after the task method completes before restarting it.</param>
        /// <param name="exceptionHandler">IManagedTaskExceptionHandler used to handle exceptions for the new task</param>
        private void StartNewLoopingTask(Action <CancellationToken> taskMethod, TimeSpan delay, IManagedTaskExceptionHandler exceptionHandler)
        {
            if (taskMethod == null)
            {
                throw new ArgumentNullException(nameof(taskMethod));
            }
            if (delay == null)
            {
                throw new ArgumentNullException(nameof(delay));
            }
            if (delay.CompareTo(TimeSpan.Zero) == delay.CompareTo(TimeSpan.MaxValue))
            {
                throw new ArgumentOutOfRangeException(nameof(delay));
            }

            _tasks.Add(
                Task.Factory.StartNew(
                    async() =>
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    try
                    {
                        taskMethod(_cancellationTokenSource.Token);
                    }
                    catch (Exception ex)
                    {
                        exceptionHandler?.HandleException(ex);
                    }

                    await Task.Delay(delay, _cancellationTokenSource.Token);
                }
            }
                    )
                );
        }