Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda