Perform another action during a await Task.Delay

Asked

Viewed 291 times

3

I’m making an application where comes a certain part of the code I need to put a:

 await Task.Delay(tempo);

But at the same time I have to wait around this time I need execute an action every 10 minutes. inserir a descrição da imagem aqui

I’ve broken my head thinking about how I can do this and nothing came to mind.

I wonder if it is possible to do this and how.

  • Calls another thread with some activity to run in parallel.

2 answers

6


Good morning, So you informed you need a new thread to carry out the 10 minute action. In this case you have two simple possibilities to use:

  • Task: you create a new Task library System.Threading.Tasks with a while and a await Task.Delay(tempo); so the task will be executed constantly, in the case of the task it executes the action and after fully executed the action will arrive at the delay and wait for the given time;

    Task _task_execucao_reading;

    void main(){
        _task_execucao_leitura = tf.StartNew(this.metodo_desejado);
    }
    
    async void metodo_desejado(){
        while (true)
        {
            await Task.Delay(_tempo_ler_dados);
            ação desejada
        }
    }
    
  • Timer: another option to use a Timer of the library of System.Threading this action executes an action in a given interval, at the end of the interval the action is executed again, whether it was completed in the first execution or not;

    Timer timerLeitura;

    void main(){
     timerLeitura = new Timer(new TimerCallback(leituraMetodo), null, tempoInicio, tempoLeitura);
    
    }
    
    void leituraMetodo(object obj)
    {
        ação desejada
    }
    

2

You can do it this way too:

void DoWorkPollingTask()
{
    Task.Run(async () =>
    {
        while (true)
        {
            // Faça alguma coisa...
            await Task.Delay(time_to_sleep);
        }
    });
}

This way you will run the method asynchronously and in parallel with other activities.

Browser other questions tagged

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