Why? Did I misunderstand something?
Run the following code, you will find that the final result is never output, which seems to cause a deadlock.
update: Please run TestSemaphoreSlimForMixUse() a few more times, as I find it occasionally works fine.
Define a method to call SemaphoreSlim.Wait:
static void TestMethod(SemaphoreSlim sp, Action worker)
{
sp.Wait();
try
{
worker();
}
finally
{
sp.Release();
}
}
Define a method to call SemaphoreSlim.WaitAsync:
static async Task TestMethodAsync(SemaphoreSlim sp, Func<Task> worker)
{
await sp.WaitAsync().ConfigureAwait(false);
try
{
await worker();
}
finally
{
sp.Release();
}
}
Method used for testing: Testing found that if you use one alone, you don't have a problem, and if you use both (mixed), you do.
public static async Task TestSemaphoreSlimForMixUse()
{
var taskList = new List<Task>();
var countList = new List<int>();
SemaphoreSlim sp = new SemaphoreSlim(1, 1);
for (int i = 0; i < 1000; i++)
{
var t = Task.Run(async () =>
{
//Note: The following two lines of code, if enabled together, cause the problem described. If only one of them is enabled, there is no problem.
//await TestMethodAsync(sp, async () => { countList.Add(Environment.CurrentManagedThreadId); await Task.FromResult(0); });
//TestMethod(sp, () => { countList.Add(Environment.CurrentManagedThreadId); });
});
taskList.Add(t);
}
await Task.WhenAll(taskList);
Console.WriteLine($"Count:{countList.Count}");
}
My theory is that when the number of tasks is higher than the maximum number of threads using for running task parallelly, it can cause deadlock in this case.
For example, if you have 1000 tasks but only 4 threads to run all tasks. It is possible that all 4 threads are waiting at TestMethod for the lock to be released, while the lock is already released for TestMethodAsync in some other task but there is no thread available to continue that task because they are all waiting for the lock, hence deadlock.