Skip to content

Instantly share code, notes, and snippets.

@Orlys
Created May 11, 2024 18:16
Show Gist options
  • Save Orlys/dcc4e2fbba3483349d5a528d61f34965 to your computer and use it in GitHub Desktop.
Save Orlys/dcc4e2fbba3483349d5a528d61f34965 to your computer and use it in GitHub Desktop.
計算線上人數用中介層
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
public class OnlineUserCounterMiddleware
{
private RequestDelegate _next;
private static int s_onlineUserCount;
public OnlineUserCounterMiddleware(
RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 僅限單機,多機請用 Redis 處理,但邏輯一樣
var currentOnlineUserCount = Interlocked.Increment(ref s_onlineUserCount);
context.Items["OnlineUser"] = currentOnlineUserCount;
await _next(context);
Interlocked.Decrement(ref s_onlineUserCount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment