- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Task.Run(Test);
Console.ReadKey();
}
public static async Task Test()
{
var semahore = new SemaphoreSlim(0, 1);
Console.WriteLine("before");
await semahore.WaitAsync();
Console.WriteLine("after");
}
}
}
我创建了一个限制为 1 和当前值为 0 的信号量。它应该允许 1 个线程通过,对吗?为什么在这个例子中没有?
最佳答案
I create a semaphore with limit 1 and current value of 0. It should allow 1 thread to pass, right?
否 - 当前值为 0,与您所写的完全相同。
信号量值在等待时计数下降 - 计数实际上是“可获取的 token 数”。来自docs :
The count is decremented each time a thread enters the semaphore, and incremented each time a thread releases the semaphore. To enter the semaphore, a thread calls one of the
Wait
orWaitAsync
overloads. To release the semaphore, it calls one of the Release overloads. When the count reaches zero, subsequent calls to one of the Wait methods block until other threads release the semaphore.
如果你想创建一个信号量,它会立即允许一个线程等待它并“通过”,你应该用初始值 1 来创建它,而不是 0。
关于c# - 为什么这个 SemaphoreSlim 会无限期地等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210048/
我正在对用 Java 语言编写的程序进行逆向工程。到目前为止,一切都很有意义,除了一段我根本无法理解的代码。该程序本身是流行游戏Minecraft的服务器,尽管我强烈认为这个问题与其本身无关。让我向您
在 Python 的时间模块中,有一个 sleep() 函数,可以让 Python 等待 x 秒后再继续执行程序。有没有办法无限期地执行此操作直到满足条件?例如: while True: ti
我有一个 php 脚本,它可能需要 2 到 10 分钟才能执行。它从网络上获取信息,因此它的时间取决于许多其他事物的通话速度。 我曾经每 15 分钟在 cron 上运行一次脚本,但有时只需要 2 分钟
我运行 Mac OSX 10.7 和 Xcode 4.2.1,一切都很好,直到几个小时前,当我尝试运行模拟器时,我的 xcode 突然挂起!这是发生了什么 代码构建成功,但它无限期地显示“Attach
我目前正在阅读 Ivor Horton 的 Beginning C。无论如何,我不确定的 for 在继续之前打印了我的 printf 语句两次。我确定我做错了什么,但我直接从书中复制了代码。如果重要的
我正在使用一个在下面设置 session 变量/cookie 的登录系统。 Chrome,它可以让你轻松地查看你的 cookie,显然将其标记为“当我关闭浏览器时”过期的 PHPSESSID。果然,当
任务是:尝试使用最基本的形式(如“ping 8.8.8.8”)在 python 中发送 ping。一段时间后终止 ping 命令(在终端中,将执行 Ctrl+C)并获得其输出。显示 ping 统计信息
我是一名优秀的程序员,十分优秀!