-1

Could someone explain to me why this code does not block UI ? Im not creating any new thread/task and application just works fine.

private void button1_Click(object sender, EventArgs e)
{
    Test1();
}

private async void Test1()
{
    var random = new Random();
    while (true)
    {
        try
        {
            textBox1.Text = random.Next(1, 100).ToString();
            textBox2.Text = random.Next(1, 100).ToString();
            await Task.Delay(5000);
        }
        catch (Exception)
        {
            break;
            throw;
        }
    }
}
PoLáKoSz
  • 355
  • 1
  • 6
  • 7
TjDillashaw
  • 787
  • 1
  • 12
  • 29
  • 2
    http://stackoverflow.com/questions/25115446/await-task-delay-helps-in-ui-refresh-faster-but-how – Habib Feb 15 '17 at 18:43
  • I have check my mailbox every single day. I check it and then after a day has gone by, I need to check it again. How am I ever able to do anything other than check my mail if I have such a requirement? Having a requirement to do something in X minutes/seconds/days/etc. doesn't mean you can't do anything between now and then. – Servy Feb 15 '17 at 18:43
  • There are **many** Q&A on Stack Overflow already, not to mention the wealth of information on the Internet, which explains how `async` and `await` work together to allow code to be written in an apparently synchronous, blocking manner without actually blocking the thread. See marked duplicate for one of the more popular ones. – Peter Duniho Feb 15 '17 at 18:52

1 Answers1

3

Im not creating any new thread/task

Well, sort of... Task.Delay does create a new task - one that completes after 5 seconds.

Your code then calls await on that task, which returns from Test1. For more information about how await works, see my async intro.

During those 5 seconds, your UI thread is free to do other work (like respond to user input). At the end of those 5 seconds, the task returned from Task.Delay completes, and the UI thread resumes executing Test1.

On a side note, you should avoid async void; in general, only use async void for event handlers. See my article on async best practices for more information.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810