gpt4 book ai didi

c# - 限制重复请求

转载 作者:行者123 更新时间:2023-11-30 20:48:18 27 4
gpt4 key购买 nike

我正在寻找一种方法来限制 HttpModule 中的重复请求。不幸的是,我不断收到以下错误:我正在寻找一个有解释的解决方案。

System.ObjectDisposedException: The semaphore has been disposed.

System.ObjectDisposedException: The semaphore has been disposed. at System.Threading.SemaphoreSlim.CheckDispose() at System.Threading.SemaphoreSlim.Release(Int32 releaseCount) at System.Threading.SemaphoreSlim.Release()

我的做法如下。

// Container for semaphores
private static readonly ConcurrentDictionary<string, SemaphoreSlim>
SemaphoreSlims = new ConcurrentDictionary<string, SemaphoreSlim>();

// Wrapper for getting semaphore
private static SemaphoreSlim GetSemaphoreSlim(string id)
{
return SemaphoreSlims.GetOrAdd(id, new SemaphoreSlim(1, 1));
}


private async Task ProcessImageAsync(HttpContext context)
{
// `hash` is the request path hashed.
SemaphoreSlim semaphore = GetSemaphoreSlim(hash);
await semaphore.WaitAsync();

try
{

// Do awaitable task

}
finally
{
semaphore.Release();
}
}

Dispose() 仅在处理 httpModule 本身期间(由我)调用。

private void Dispose(bool disposing)
{
if (this.isDisposed)
{
return;
}

if (disposing)
{
// Dispose of any managed resources here.
foreach (KeyValuePair<string, SemaphoreSlim> semaphore in SemaphoreSlims)
{
semaphore.Value.Dispose();
}

SemaphoreSlims.Clear();
}

// Call the appropriate methods to clean up
// unmanaged resources here.
// Note disposing is done.
this.isDisposed = true;
}

最佳答案

Apparently, both HttpApplication and HttpModule's are instantiated multiple times. (这种设计在我看来非常有问题。换句话说,这是 ASP.NET 中的一个设计缺陷。这些实例应该像每个人所期望的那样是单例。)

静态字典正在被释放的多个实例处理。

您根本不需要处置。只需让操作系统在工作进程死亡时删除这些资源即可。

不是,你的字典会无限增长。

此外,您传递给 GetOrAdd 的信号量实例几乎总是会在未被处置的情况下泄漏。

关于c# - 限制重复请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com