run Task.Whenall wait and then run back

Asked

Viewed 597 times

0

I’m trying to make a console program, run a task, wait and run again and continue in this cycle endlessly.

In theory it would place the function within a While(true) infinite loop, but as the function is asynchronous is not working.

    private static void Main(string[] args)
            {
        While(true)
        {
        ChamaTarefas();
System.Threading.Thread.Sleep(10000);
        }

    }
    private static async Task ChamaTarefas()
         {
           IEnumerable<UrlsProdutos> registros = db.UrlsTable.Where(w => w.Lido == false).Take(10);

            var tarefas = registros.Select((registro, index) =>
            {
                return Task.Run(async () => await ExecutaTarefasAsync(registro, index));
            });

         await Task.WhenAll(tarefas.ToArray());
    }



    public static async Task ExecutaTarefasAsync(UrlsProdutos registros, int index)
        {
         var produto = await ExtraiDados.ParseHtml(registros.Url, index);

         InsertAdo.MarcaComoLidoStpAsync(registros.UrlsImoveisVivarealId, index);
         await InsertAdo.InsertAdoStpAsync(produto, index);
         await ManipulacaoFoto.DownloadImgAsync(produto.FotosProduto, index);

       }

But of course it didn’t work, it runs the task, waits 10 seconds and is already creating another task, I tried to do something like:

var executando = ChamaTarefas();

    if(executando.IsCompleted)
  • particularly I found very confusing the explanation of the question. What do you mean by "continue in this cycle"? I couldn’t understand exactly where your doubt is. In time: it’s not bad to use windows Scheduler. It possess much more advanced features than we can implement alone and fast. There are alternatives in . NET with advanced task scheduling features. Have a look at: http://www.quartz-scheduler.net/

  • in case it is like executing an instruction, wait, run again.

1 answer

3


If your goal is to wait ChamaTarefas() complete and then wait for 10s more, add Wait() on your call on Main():

private static void Main(string[] args)
{
    while(true)
    {
        // Chamar wait faz a thread bloquear até a tarefa ser completada.
        ChamaTarefas().Wait(); 
        System.Threading.Thread.Sleep(10000);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.