- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了一个问题,我需要限制对另一个网络服务器的调用次数。它会有所不同,因为服务器是共享的,并且可能具有更多或更少的容量。
我正在考虑使用 SemaphoreSlim 类,但没有公共(public)属性可以更改最大计数。
我应该将我的 SemaphoreSlim 类包装在另一个处理最大计数的类中吗?有没有更好的方法?
编辑:
这是我正在尝试的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Semaphore
{
class Program
{
static SemaphoreSlim _sem = new SemaphoreSlim(10,10000);
static void Main(string[] args)
{
int max = 15;
for (int i = 1; i <= 50; i++)
{
new Thread(Enter).Start(new int[] { i, max});
}
Console.ReadLine();
max = 11;
for (int i = 1; i <= 50; i++)
{
new Thread(Enter).Start(new int[] { i, max });
}
}
static void Enter(object param)
{
int[] arr = (int[])param;
int id = arr[0];
int max = arr[1];
try
{
Console.WriteLine(_sem.CurrentCount);
if (_sem.CurrentCount <= max)
_sem.Release(1);
else
{
_sem.Wait(1000);
Console.WriteLine(id + " wants to enter");
Thread.Sleep((1000 * id) / 2); // can be here at
Console.WriteLine(id + " is in!"); // Only three threads
}
}
catch(Exception ex)
{
Console.WriteLine("opps ", id);
Console.WriteLine(ex.Message);
}
finally
{
_sem.Release();
}
}
}
}
问题:
1-_sem.Wait(1000) 应该取消将执行超过 1000 毫秒的线程的执行,不是吗?
2-我有没有使用 Release/Wait 的想法?
最佳答案
您不能更改最大计数,但您可以创建一个具有非常高的最大计数的 SemaphoreSlim
,并保留其中的一些。参见 this constructor .
假设并发调用的绝对最大值为 100,但最初您希望它为 25。您初始化信号量:
SemaphoreSlim sem = new SemaphoreSlim(25, 100);
所以 25 是可以并发服务的请求数。您已保留其他 75 个。
如果您想增加允许的数量,只需调用 Release(num) .如果您调用 Release(10)
,则数字将变为 35。
现在,如果您想减少可用请求的数量,您必须多次调用 WaitOne
。例如,如果您想从可用计数中删除 10:
for (var i = 0; i < 10; ++i)
{
sem.WaitOne();
}
这有可能会阻塞,直到其他客户端释放信号量。也就是说,如果您允许 35 个并发请求并希望将其减少到 25,但已经有 35 个客户端有事件请求,则 WaitOne
将阻塞,直到客户端调用 Release
,直到释放 10 个客户端,循环才会终止。
关于c# - 具有动态 maxCount 的 SemaphoreSlim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24067200/
我想在 Codility 上尝试一些挑战,并从头开始。所有作业都相对容易,直到名为 MaxCounters 的作业为止。我不认为这个特别难,尽管它是第一个标记为非无痛的。 我已阅读task并开始使用
我遇到了一个问题,我需要限制对另一个网络服务器的调用次数。它会有所不同,因为服务器是共享的,并且可能具有更多或更少的容量。 我正在考虑使用 SemaphoreSlim 类,但没有公共(public)属
我有以下问题: 你有 N 个计数器,初始设置为 0,你可以对它们进行两种可能的操作: increase(X) − counter X is increased by 1, max co
你得到一个计数器数组N,从零开始。 您有一个要在 N 数组上执行的操作列表 A。 每个 Action 都是一个 int x 即 A = [1,5,3] 对于 A 中的每个 k 作为 x 操作 如果 x
如何使用 maxCount 重试网络请求(某种失败),例如。 5 次或直到服务器使用 RxSwift 的 retry 运算符返回我想要的内容。 我想做的是: 当成功变为“ok”时,停止重试并立即发出q
我并没有真正从 cv::calcOpticalFlowPyrLK 中的 criteria 得到什么是 epsilon 和 maxCount。有人可以给我更多相关信息吗? openCV 文档中的定义对我
这是我在 Codility 类(class)中使用的代码:MaxCounters def solution(N, A): counters = [0] * N max_c = 0
我是一名优秀的程序员,十分优秀!