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

190
Visualizações
What is a good alternative to await Task.Run executing an asyncronous lambda?

I'm in the process of upgrading old code using BackgroundWorker. Following a series of articles from Stephen Cleary on this matter, I think the ideal substitute in this case is Task.Run().

Mine is a Windows Forms application. When a Form is constructed, different background operations are started and their results are collected in different event handlers, as per the BackgroundWorker pattern.

Now, my new methods follow the async/await pattern. I have some concerns about calling Task.Run() on an async methods.

private async void FormEventHandler(object sender, EventArgs e)
{
    Task.Run(async () => await AwaitableLongRunningTask_1());
    Task.Run(async () => await AwaitableLongRunningTask_2());
    //...
}

AwaitableLongRunningTask_1 and _2 needs to be async, since the calls they makes within the method body are to async methods.

I can't call them in a simple await succession:

private async void FormEventHandler(object sender, EventArgs e)
{
    await AwaitableLongRunningTask_1();
    await AwaitableLongRunningTask_2();
    //...
}

since they need to be started in parallel and they're obviously long running tasks spanning several seconds.

So my question is, do I need to refactor AwaitableLongRunningTasks to be non-async void, changing their internal behaviour like suggested here in "How to call asynchronous method from synchronous method"? Are there better options I'm missing?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use Task.WhenAll

private async void FormEventHandler(object sender, EventArgs e)
{
    await Task.WhenAll( 
            AwaitableLongRunningTask_1(), 
            AwaitableLongRunningTask_2());

}
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