|
| 1 | +// Copyright (C) 2024-2025 ZenonEl |
| 2 | +// This program is free software: you can redistribute it and/or modify |
| 3 | +// it under the terms of the GNU Affero General Public License as published |
| 4 | +// by the Free Software Foundation, either version 3 of the License, or |
| 5 | +// (at your option) any later version. |
| 6 | + |
| 7 | +// Эта программа является свободным программным обеспечением: вы можете распространять и/или изменять |
| 8 | +// её на условиях Стандартной общественной лицензии GNU Affero, опубликованной |
| 9 | +// Фондом свободного программного обеспечения, либо версии 3 лицензии, либо |
| 10 | +// (по вашему выбору) любой более поздней версии. |
| 11 | + |
| 12 | +namespace TelegramMediaRelayBot |
| 13 | +{ |
| 14 | + public static class DownloadQueue |
| 15 | + { |
| 16 | + private static SemaphoreSlim _semaphore = null!; |
| 17 | + private static int _queuedCount = 0; |
| 18 | + |
| 19 | + public static void Initialize(int maxConcurrent) |
| 20 | + { |
| 21 | + _semaphore = new SemaphoreSlim(maxConcurrent, maxConcurrent); |
| 22 | + } |
| 23 | + |
| 24 | + public static async Task<T?> EnqueueAsync<T>( |
| 25 | + Func<Task<T?>> downloadFunc, |
| 26 | + Action<int>? onQueued = null, |
| 27 | + CancellationToken ct = default) |
| 28 | + { |
| 29 | + int position = Interlocked.Increment(ref _queuedCount); |
| 30 | + try |
| 31 | + { |
| 32 | + if (_semaphore.CurrentCount == 0) |
| 33 | + onQueued?.Invoke(position); |
| 34 | + |
| 35 | + await _semaphore.WaitAsync(ct); |
| 36 | + Interlocked.Decrement(ref _queuedCount); |
| 37 | + |
| 38 | + return await downloadFunc(); |
| 39 | + } |
| 40 | + finally |
| 41 | + { |
| 42 | + _semaphore.Release(); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public static int QueuedCount => _queuedCount; |
| 47 | + public static int ActiveCount => Config.maxConcurrentDownloads - _semaphore.CurrentCount; |
| 48 | + } |
| 49 | +} |
0 commit comments