namespace NetAdmin.Host.Middlewares;
///
/// 安全停机中间件
///
///
/// 放在所有中间件最前面
///
public sealed class SafetyShopHostMiddleware(RequestDelegate next)
{
private static long _connections;
private static bool _hostStopping;
///
/// 当前连接数
///
public static long Connections => Interlocked.Read(ref _connections);
///
/// 停机处理
///
public static void OnStopping()
{
Volatile.Write(ref _hostStopping, true);
while (Interlocked.Read(ref _connections) > 0) {
Thread.Sleep(10);
}
}
///
/// 主函数
///
public async Task InvokeAsync(HttpContext context)
{
if (Volatile.Read(ref _hostStopping)) {
context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
return;
}
_ = Interlocked.Increment(ref _connections);
await next(context).ConfigureAwait(false);
_ = Interlocked.Decrement(ref _connections);
}
}