using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.Scanner.ScanMiddlewares
{
///
/// 扫描并发限制中间件
///
[Service(ServiceLifetime.Singleton)]
sealed class ConcurrentMiddleware : IMiddleware
{
private readonly SemaphoreSlim semaphoreSlim;
///
/// 扫描并发限制中间件
///
public ConcurrentMiddleware()
{
var currentCount = Environment.ProcessorCount * 2;
this.semaphoreSlim = new SemaphoreSlim(currentCount, currentCount);
}
///
/// 限制描并发扫
///
///
///
///
public async Task InvokeAsync(GithubContext context, Func next)
{
try
{
await this.semaphoreSlim.WaitAsync(context.CancellationToken);
await next();
}
finally
{
this.semaphoreSlim.Release();
}
}
}
}