Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait some seconds without blocking UI execution

Tags:

c#

timer

wait

I would like to wait some seconds between two instruction, but WITHOUT blocking the execution.

For example, Thread.Sleep(2000) it is not good, because it blocks execution.

The idea is that I call a method and then I wait X seconds (20 for example) listening for an event coming. At the end of the 20 seconds I should do some operation depending on what happened in the 20 seconds.

like image 823
user3376691 Avatar asked Mar 03 '14 21:03

user3376691


3 Answers

I think what you are after is Task.Delay. This doesn't block the thread like Sleep does and it means you can do this using a single thread using the async programming model.

async Task PutTaskDelay()
{
    await Task.Delay(5000);
} 

private async void btnTaskDelay_Click(object sender, EventArgs e)
{
    await PutTaskDelay();
    MessageBox.Show("I am back");
}
like image 140
daniellepelley Avatar answered Nov 14 '22 15:11

daniellepelley


I use:

private void WaitNSeconds(int segundos)
{
    if (segundos < 1) return;
    DateTime _desired = DateTime.Now.AddSeconds(segundos);
    while (DateTime.Now < _desired) {
         System.Windows.Forms.Application.DoEvents();
    }
}
like image 32
Omar Avatar answered Nov 14 '22 15:11

Omar


This is a good case for using another thread:

// Call some method
this.Method();

Task.Factory.StartNew(() =>
{
    Thread.Sleep(20000);

    // Do things here.
    // NOTE: You may need to invoke this to your main thread depending on what you're doing
});

The above code expects .NET 4.0 or above, otherwise try:

ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
    Thread.Sleep(20000);

    // Do things here
}));
like image 15
Matt Avatar answered Nov 14 '22 15:11

Matt