【发布时间】:2013-12-06 00:59:53
【问题描述】:
我一直在尝试使用信号量来控制我的服务可以处理的请求数量。即。
class Service : IDisposable {
SemaphoreSlim s = new SemaphoreSlim(InitialCapacity);
....
async void ProcessRequest() {
await s.WaitAsync();
try {
......
} finally {
s.Release();
}
}
}
我遇到了 2 个问题,我不知道如何解决。我一直在使用类似的 hack 来解决这些问题,但我想知道是否有更好的方法
-
我希望能够动态改变我的服务类的容量,所以我有这样的东西。
void ChangeCapacity(int newCapacity) { int extraRequestsCount = newCapacity - oldCapacity; if (extraRequestsCount > 0) { s.Release(extraRequestsCount); } else if (extraRequestsCount < 0) { for (int i = 0; i < -extraRequestsCount; i++) { s.WaitAsync(); // try to steal some resources, over time... } } } -
在 dispose 方法中,我想确保所有请求处理在我处理信号量之前完成,否则我的 ProcessRequest() 中的 s.Release() 调用会抛出 ObjectDisposedException,所以我做了以下操作
public void Dispose() { if (s!= null) { for (int i = 0; i < oldCapacity; i++) { s.Wait(); } s.Dispose(); } }
请注意,我一直在使用循环手动等待很多次。如果容量很大,这真的很慢。有一个更好的方法吗?信号量有一个 Release(int count) 为什么没有 Wait(int count)?
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# concurrency thread-safety locking semaphore