| | | 1 | | using Microsoft.Extensions.DependencyInjection; |
| | | 2 | | |
| | | 3 | | namespace Elsa.Common.Multitenancy.EventHandlers; |
| | | 4 | | |
| | | 5 | | public class RunBackgroundTasks : ITenantActivatedEvent, ITenantDeactivatedEvent |
| | | 6 | | { |
| | 1 | 7 | | private readonly ICollection<Task> _runningTasks = new List<Task>(); |
| | | 8 | | private CancellationTokenSource _cancellationTokenSource = default!; |
| | | 9 | | |
| | | 10 | | public Task TenantActivatedAsync(TenantActivatedEventArgs args) |
| | | 11 | | { |
| | 1 | 12 | | var cancellationToken = args.CancellationToken; |
| | 1 | 13 | | _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 14 | | |
| | 1 | 15 | | var tenantScope = args.TenantScope; |
| | 1 | 16 | | var backgroundTasks = tenantScope.ServiceProvider.GetServices<IBackgroundTask>(); |
| | 1 | 17 | | var backgroundTaskStarter = tenantScope.ServiceProvider.GetRequiredService<IBackgroundTaskStarter>(); |
| | 1 | 18 | | var taskExecutor = tenantScope.ServiceProvider.GetRequiredService<ITaskExecutor>(); |
| | | 19 | | |
| | 4 | 20 | | foreach (var backgroundTask in backgroundTasks) |
| | | 21 | | { |
| | 1 | 22 | | var task = backgroundTaskStarter |
| | 1 | 23 | | .StartAsync(backgroundTask, _cancellationTokenSource.Token) |
| | 2 | 24 | | .ContinueWith(t => taskExecutor.ExecuteTaskAsync(backgroundTask, _cancellationTokenSource.Token), cancel |
| | 2 | 25 | | if (!task.IsCompleted) _runningTasks.Add(task); |
| | | 26 | | } |
| | | 27 | | |
| | 1 | 28 | | return Task.CompletedTask; |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public Task TenantDeactivatedAsync(TenantDeactivatedEventArgs args) |
| | | 32 | | { |
| | 1 | 33 | | _cancellationTokenSource.Cancel(); |
| | 1 | 34 | | _runningTasks.Clear(); |
| | 1 | 35 | | return Task.CompletedTask; |
| | | 36 | | } |
| | | 37 | | } |