Beispiel #1
0
        private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
        {
            var taskFactory   = new TaskFactory(TaskScheduler.Current);
            var referenceTime = DateTime.UtcNow;

            var tasksThatShouldRun = _scheduledTasks.Where(t => t.ShouldRun(referenceTime)).ToList();

            foreach (var taskThatShouldRun in tasksThatShouldRun)
            {
                taskThatShouldRun.Increment();

                await taskFactory.StartNew(
                    async() =>
                {
                    try
                    {
                        await taskThatShouldRun.Task.ExecuteAsync(cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        var args = new UnobservedTaskExceptionEventArgs(
                            ex as AggregateException ?? new AggregateException(ex));

                        UnobservedTaskException?.Invoke(this, args);

                        if (!args.Observed)
                        {
                            throw;
                        }
                    }
                },
                    cancellationToken);
            }
        }
		internal static void PublishUnobservedTaskException(Exception ex) {
			if (ex != null) {
				if (!PropagateOperationCanceledException && ex is OperationCanceledException) {
					return;
				}

				if (UnobservedTaskException != null) {
					#if !UniRxLibrary

					if (Thread.CurrentThread.ManagedThreadId == PlayerLoopHelper.MainThreadId) {
						// allows inlining call.
						UnobservedTaskException.Invoke(ex);
					} else {
						// Post to MainThread.
						PlayerLoopHelper.UnitySynchronizationContext.Post(handleExceptionInvoke, ex);
					}

					#else
					UnobservedTaskException.Invoke(ex);
					#endif
				} else {
					#if !UniRxLibrary
					string msg = null;

					if (UnobservedExceptionWriteLogType != UnityEngine.LogType.Exception) {
						msg = "UnobservedTaskException:" + ex.ToString();
					}

					switch (UnobservedExceptionWriteLogType) {
						case UnityEngine.LogType.Error:
							UnityEngine.Debug.LogError(msg);
							break;

						case UnityEngine.LogType.Assert:
							UnityEngine.Debug.LogAssertion(msg);
							break;

						case UnityEngine.LogType.Warning:
							UnityEngine.Debug.LogWarning(msg);
							break;

						case UnityEngine.LogType.Log:
							UnityEngine.Debug.Log(msg);
							break;

						case UnityEngine.LogType.Exception:
							UnityEngine.Debug.LogException(ex);
							break;

						default:
							break;
					}

					#else
					Console.WriteLine("UnobservedTaskException:" + ex.ToString());
					#endif
				}
			}
		}
Beispiel #3
0
        private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
        {
            var taskFactory   = new TaskFactory(TaskScheduler.Current);
            var referenceTime = DateTime.UtcNow;

            foreach (var flushTask in _scheduledReporters)
            {
                if (!flushTask.ShouldRun(referenceTime))
                {
                    Logger.Trace($"Skipping {flushTask.Reporter.GetType().FullName}, next run in {flushTask.NextRunTime.Subtract(referenceTime).Milliseconds} ms");
                    continue;
                }

                flushTask.Increment();

                await taskFactory.StartNew(
                    async() =>
                {
                    try
                    {
                        Logger.Trace($"Executing reporter {flushTask.Reporter.GetType().FullName} FlushAsync");

                        var result = await flushTask.Reporter.FlushAsync(
                            _metrics.Snapshot.Get(flushTask.Reporter.Filter),
                            cancellationToken);

                        if (result)
                        {
                            _metrics.Measure.Counter.Increment(_successCounter, flushTask.Reporter.GetType().FullName);
                            Logger.Trace($"Reporter {flushTask.Reporter.GetType().FullName} FlushAsync executed successfully");
                        }
                        else
                        {
                            _metrics.Measure.Counter.Increment(_failedCounter, flushTask.Reporter.GetType().FullName);
                            Logger.Warn($"Reporter {flushTask.Reporter.GetType().FullName} FlushAsync failed");
                        }
                    }
                    catch (Exception ex)
                    {
                        _metrics.Measure.Counter.Increment(_failedCounter, flushTask.Reporter.GetType().FullName);

                        var args = new UnobservedTaskExceptionEventArgs(
                            ex as AggregateException ?? new AggregateException(ex));

                        Logger.Error($"Reporter {flushTask.Reporter.GetType().FullName} FlushAsync failed", ex);

                        UnobservedTaskException?.Invoke(this, args);

                        if (!args.Observed)
                        {
                            throw;
                        }
                    }
                },
                    cancellationToken);
            }
        }
        private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
        {
            var taskFactory   = new TaskFactory(TaskScheduler.Current);
            var referenceTime = DateTime.UtcNow;

            var tasksThatShouldRun = _scheduledTasks.Where(t => t.ShouldRun(referenceTime)).ToList();

            foreach (var taskThatShouldRun in tasksThatShouldRun)
            {
                taskThatShouldRun.Increment();

                await taskFactory.StartNew(
                    async() =>
                {
                    try
                    {
                        using (var scope = _serviceScopeFactory.CreateScope())
                        {
                            var t         = taskThatShouldRun.Task.GetType();
                            var method    = t.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);
                            var arguments = method.GetParameters()
                                            .Select(a =>
                                                    a.ParameterType == typeof(CancellationToken)
                                                                                        ? cancellationToken
                                                                                        : scope.ServiceProvider.GetService(a.ParameterType))
                                            .ToArray();


                            //invoke.
                            if (typeof(Task).Equals(method.ReturnType))
                            {
                                await(Task) method.Invoke(taskThatShouldRun.Task, arguments);
                            }
                            else
                            {
                                method.Invoke(taskThatShouldRun.Task, arguments);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "BackgroundTask Error");

                        var args = new UnobservedTaskExceptionEventArgs(
                            ex as AggregateException ?? new AggregateException(ex));

                        UnobservedTaskException?.Invoke(this, args);

                        if (!args.Observed)
                        {
                            throw;
                        }
                    }
                },
                    cancellationToken);
            }
        }
Beispiel #5
0
        internal static void PublishUnobservedTaskException(Exception ex)
        {
            if (ex != null)
            {
                if (!PropagateOperationCanceledException && ex is OperationCanceledException)
                {
                    return;
                }

                if (UnobservedTaskException != null)
                {
                    if (Thread.CurrentThread.ManagedThreadId == PlayerLoopHelper.MainThreadId)
                    {
                        // allows inlining call.
                        UnobservedTaskException.Invoke(ex);
                    }
                    else
                    {
                        // Post to MainThread.
                        PlayerLoopHelper.UnitySynchronizationContext.Post(handleExceptionInvoke, ex);
                    }
                }
                else
                {
                    string msg = null;
                    if (UnobservedExceptionWriteLogType != LogType.Exception)
                    {
                        msg = "UnobservedTaskException:" + ex;
                    }
                    switch (UnobservedExceptionWriteLogType)
                    {
                    case LogType.Error:
                        Debug.LogError(msg);
                        break;

                    case LogType.Assert:
                        Debug.LogAssertion(msg);
                        break;

                    case LogType.Warning:
                        Debug.LogWarning(msg);
                        break;

                    case LogType.Log:
                        Debug.Log(msg);
                        break;

                    case LogType.Exception:
                        Debug.LogException(ex);
                        break;
                    }
                }
            }
        }
Beispiel #6
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                var taskFactory   = new TaskFactory(TaskScheduler.Current);
                var referenceTime = DateTime.Now;

                var tasksThatShouldRun = _scheduledTasks.Where(t => t.ShouldRun(referenceTime)).ToList();

                foreach (var taskThatShouldRun in tasksThatShouldRun)
                {
                    var currentTask = taskThatShouldRun.CurrenTask;

                    if (currentTask != null && !TaskStatuses.FinishedStatuses.Contains(currentTask.Status))
                    {
                        continue;
                    }

                    if (currentTask?.IsCompleted == true)
                    {
                        currentTask.Dispose();
                    }
                    taskThatShouldRun.SetNextRunTime();
                    taskThatShouldRun.CurrenTask = taskFactory
                                                   .StartNew(
                        async() =>
                    {
                        try
                        {
                            await taskThatShouldRun.RunTask(cancellationToken);
                        }
                        catch (Exception ex)
                        {
                            var args = new UnobservedTaskExceptionEventArgs(
                                ex as AggregateException ?? new AggregateException(ex));

                            UnobservedTaskException?.Invoke(this, args);

                            if (!args.Observed)
                            {
                                throw;
                            }
                        }
                    },
                        cancellationToken)
                                                   .Unwrap();
                }

                await Task.Delay(TimeSpan.FromSeconds(RecurrenceInSecs), cancellationToken);
            }
        }
        private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
        {
            var taskFactory   = new TaskFactory(TaskScheduler.Current);
            var referenceTime = DateTime.UtcNow;

            foreach (var reportTask in _scheduledReporters)
            {
                if (!reportTask.ShouldRun(referenceTime))
                {
                    Logger.Trace($"Skipping {reportTask.Reporter.GetType().FullName}, next run in {reportTask.NextRunTime.Subtract(referenceTime).Milliseconds} ms");
                    continue;
                }

                reportTask.Increment();

                await taskFactory.StartNew(
                    async() =>
                {
                    try
                    {
                        Logger.Trace($"Executing reporter {reportTask.Reporter.GetType().FullName}");

                        var healthStatus = await _healthRoot.HealthCheckRunner.ReadAsync(cancellationToken);

                        await reportTask.Reporter.ReportAsync(_healthRoot.Options, healthStatus, cancellationToken);

                        Logger.Trace($"Reporter {reportTask.Reporter.GetType().FullName} executed successfully");
                    }
                    catch (Exception ex)
                    {
                        var args = new UnobservedTaskExceptionEventArgs(
                            ex as AggregateException ?? new AggregateException(ex));

                        Logger.Error($"Reporter {reportTask.Reporter.GetType().FullName} failed", ex);

                        UnobservedTaskException?.Invoke(this, args);

                        if (!args.Observed)
                        {
                            throw;
                        }
                    }
                },
                    cancellationToken);
            }
        }
        private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
        {
            var taskFactory   = new TaskFactory(TaskScheduler.Current);
            var referenceTime = DateTime.UtcNow;

#if DEBUG
            Debug.WriteLine("ExecuteOnceAsync ");
#endif

            var tasksThatShouldRun = _scheduledTasks.Where(t => t.ShouldRun(referenceTime) && !t.Task.IsRunning).ToList();

            foreach (var taskThatShouldRun in tasksThatShouldRun)
            {
                taskThatShouldRun.Increment();

#if DEBUG
                Debug.WriteLine("Start  " + taskThatShouldRun.Task.ToString());
#endif
                await taskFactory.StartNew(
                    async() =>
                {
                    try
                    {
                        await taskThatShouldRun.Task.ExecuteAsync(cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        var args = new UnobservedTaskExceptionEventArgs(
                            ex as AggregateException ?? new AggregateException(ex));

                        UnobservedTaskException?.Invoke(this, args);

                        if (!args.Observed)
                        {
                            throw;
                        }
                    }
                },
                    cancellationToken);

#if DEBUG
                Debug.WriteLine("executed  " + taskThatShouldRun.Task.ToString());
#endif
            }
        }
Beispiel #9
0
        private async Task ExecuteTask(ScheduledTaskWrapper taskWrapper, ScheduleMode mode, CancellationToken cancellationToken, params object[] args)
        {
            try
            {
                if (taskWrapper.Task is ScheduledTask)
                {
                    var task  = taskWrapper.Task as ScheduledTask;
                    var count = task.Pipeline.Count();
                    var msg   = $"Starting task {task.GetType().Name} [{mode.ToString()}]";
                    if (count > 1)
                    {
                        msg = $"{msg} (pipeline of {task.Pipeline.Count()} items)";
                        //log.LogInformation($"Starting task {task.GetType().Name} (pipeline of {task.Pipeline.Count()} items)");
                    }
                    log.Information(msg);
                }
                var sw = new Stopwatch();
                using (var sm = new SemaphoreSlim(1, 1))
                {
                    await sm.WaitAsync();

                    taskWrapper.IsRunning = true;
                    //taskWrapper.Task.SetMode()
                    sw.Start();
                    await taskWrapper.Task.ExecuteAsync(mode, cancellationToken, args);

                    sw.Stop();
                    taskWrapper.IsRunning = false;
                    log.Information($"Task {taskWrapper.Task.GetType().Name} completed in {sw.Elapsed}, will run next at {taskWrapper.NextRunTime.ToLocalTime().ToDefaultWithTime()}");
                }
            }
            catch (Exception ex)
            {
                var ex_args = new UnobservedTaskExceptionEventArgs(
                    ex as AggregateException ?? new AggregateException(ex));

                UnobservedTaskException?.Invoke(this, ex_args);

                if (!ex_args.Observed)
                {
                    throw;
                }
            }
        }
Beispiel #10
0
        // Derived classes should override this and execute a long running method until
        // cancellation is requested
        protected async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    await _taskToExecute.ExecuteAsync(cancellationToken);
                }
                catch (Exception ex)
                {
                    var args = new UnobservedTaskExceptionEventArgs(
                        ex as AggregateException ?? new AggregateException(ex));

                    UnobservedTaskException?.Invoke(this, args);

                    if (!args.Observed)
                    {
                        throw;
                    }
                }
                await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
            }
        }
        private async Task ExecuteOnceAsync(CancellationToken stoppingToken)
        {
            var referenceTime = DateTimeOffset.UtcNow;

            var scheduledTasks     = _registrations.Jobs.Values;
            var tasksThatShouldRun = scheduledTasks.Where(t => t.ShouldRun(referenceTime)).ToList();

            foreach (var taskThatShouldRun in tasksThatShouldRun)
            {
                taskThatShouldRun.Increment();

#pragma warning disable CA2008 // Do not create tasks without passing a TaskScheduler
                await _taskFactory.StartNew(
                    async() =>
                {
                    try
                    {
                        await taskThatShouldRun.ScheduledJob.ExecuteAsync(stoppingToken);
                    }
                    catch (Exception ex)
                    {
                        var args = new UnobservedTaskExceptionEventArgs(
                            ex as AggregateException ?? new AggregateException(ex));

                        UnobservedTaskException?.Invoke(this, args);

                        if (!args.Observed)
                        {
                            throw;
                        }
                    }
                },
                    stoppingToken);

#pragma warning restore CA2008 // Do not create tasks without passing a TaskScheduler
            }
        }
        ////////////////////////////////////////////////////////////
        //
        // Internal methods
        //

        // This is called by the TaskExceptionHolder finalizer.
        internal static void PublishUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs ueea)
        {
            UnobservedTaskException?.Invoke(sender, ueea);
        }
 private void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) => UnobservedTaskException?.Invoke(this, e);
        private async Task ExecuteOnceAsync(CancellationToken cancellationToken)
        {
            using (var scope = _provider.CreateScope())
            {
                var db    = scope.ServiceProvider.GetRequiredService <CrmsContext>();
                var timer = scope.ServiceProvider.GetService <ITimerService>();

                var taskFactory = new TaskFactory(TaskScheduler.Current);
                var task        = taskFactory.StartNew(() => timer?.Scheduled(), cancellationToken);
                foreach (var eventAttribute in Events)
                {
                    var type  = db.Model.FindEntityType(eventAttribute.Table.FullName);
                    var dbset =
                        (IQueryable <object>)
                        db
                        .GetType()
                        .GetRuntimeProperties()
                        .FirstOrDefault(o => o.PropertyType.IsGenericType &&
                                        o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet <>) &&
                                        o.PropertyType.GenericTypeArguments.Contains(type.ClrType))
                        ?.GetValue(db) ?? throw new Exception();
                    var realParams =
                        dbset
                        .Where(e =>
                               TimeInInterval((DateTime)type.GetProperties()
                                              .Single(p => p.Name == eventAttribute.TimeColumn && p.ClrType == typeof(DateTime))
                                              .PropertyInfo.GetValue(e)))
                        .Where(e => eventAttribute.WhereColumns
                               .Select(col => col.StartsWith("!") ? Tuple.Create(col.Substring(1), true) : Tuple.Create(col, false))
                               .Select(ci => ci.Item2 ^ Convert.ToBoolean(type.GetProperties().Single(ppt => ppt.Name == ci.Item1).PropertyInfo.GetValue(e))).All(b => b))
                        .Select(e =>
                                eventAttribute.ParamColumns.Select(col => e.GetType().GetProperty(col).GetValue(e))
                                .ToArray()).ToList();

                    foreach (var parameters in realParams)
                    {
                        var instance = scope.ServiceProvider.GetRequiredService(eventAttribute.Callback.DeclaringType);
                        await taskFactory.StartNew(
                            () =>
                        {
                            try
                            {
                                eventAttribute.Callback.Invoke(instance, parameters);
                            }
                            catch (Exception ex)
                            {
                                var args = new UnobservedTaskExceptionEventArgs(
                                    ex as AggregateException ?? new AggregateException(ex));

                                UnobservedTaskException?.Invoke(this, args);

                                if (!args.Observed)
                                {
                                    throw;
                                }
                            }
                        },
                            cancellationToken);
                    }
                }
                await task;
            }
        }
Beispiel #15
0
        private async Task ExecuteOnceAsync(IScope scope, CancellationToken cancellationToken)
        {
            var taskFactory   = new TaskFactory(TaskScheduler.Current);
            var referenceTime = DateTime.UtcNow;

            var tasksThatShouldRun = _scheduledTasks.Where(t => t.ShouldRun(referenceTime));

            // each task will have its InvokeAsync method level dependencies resolved
            // and the method will be invoked.
            // The method invocation delegate is cached and called by `DynamicInvoke`, allowing
            // the method to be called without using reflection.
            //
            // Each task is kicked off without blocking other tasks that should run at the same time.


            object now = referenceTime; // cast to object to avoid boxing multiple times when calling the logger

            foreach (var taskThatShouldRun in tasksThatShouldRun)
            {
                if (!_argumentCache.TryGetValue(taskThatShouldRun, out var methodArgumentPair))
                {
                    methodArgumentPair = ExtractInvocationInfo(taskThatShouldRun);

                    _argumentCache[taskThatShouldRun] = methodArgumentPair;
                }

                var arguments = methodArgumentPair.ArgumentTypes
                                .Select(t => t == typeof(CancellationToken) ? cancellationToken : scope.GetInstance(t))
                                .ToArray();

                taskThatShouldRun.Increment();


                Stopwatch sw = null;

#pragma warning disable AsyncFixer05 // Downcasting from a nested task to an outer task.
                await taskFactory.StartNew(
                    async() =>
                {
                    try
                    {
                        _logger.InfoFormat("Beginning Invoke of task {0} at {1} UTC", taskThatShouldRun.Task, now);
                        sw = Stopwatch.StartNew();
                        await(Task) methodArgumentPair.InvokeDelegate.DynamicInvoke(arguments);
                    }
                    catch (Exception ex)
                    {
                        _logger.WarnFormat("Task {0} threw error {1}", taskThatShouldRun, ex.Message);
                        var args = new UnobservedTaskExceptionEventArgs(
                            ex as AggregateException ?? new AggregateException(ex));

                        UnobservedTaskException?.Invoke(this, args);

                        if (!args.Observed)
                        {
                            _logger.Error(
                                "Exception was not marked as handled in the UnobservedTaskException event. Rethrowing.");
                            throw;
                        }
                    }
                    finally
                    {
                        sw?.Stop();
                        _logger.InfoFormat("Task {0} completed in {1}", taskThatShouldRun.Task, sw?.Elapsed);
                    }
                },
                    cancellationToken);

#pragma warning restore AsyncFixer05 // Downcasting from a nested task to an outer task.
            }
        }