Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
I found Calling Semaphoreslim.Wait and Semaphoreslim.WaitAsync at the same time cause a deadlock?

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}");
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda