Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WinForm C# wait 5 second

For my Win Form program, I need to wait 5 second but the normal c# Thread.Sleep(5000); doesn’t work in the Win Form so I tried Task.Delay(5000); but it still doesn’t work. Help

public void waitThen();
{
    Task.Delay(5000);
    checkForDone();
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There’s a long comment thread above, but hopefully an answer can simplify for future visitors…

Task.Delay is an asynchronous operation. (Whether or not it’s internally marked as async I can’t say for sure, but it’s "awaitable".) You just need to await it:

public async Task waitThen()
{
    await Task.Delay(5000);
    checkForDone();
}

Note also that the method now returns a Task, not void. This makes your waitThen method also awaitable, so consuming code will need to await it if that code also wants to wait until the operation is complete before continuing.


but the normal c# Thread.Sleep(5000); doesn’t work in the Win Form

Sure it does, it always has. However, unless it’s done on a separate thread explicitly then it will also freeze the UI for 5 seconds. Which "works" but is certainly not ideal. Relying on Task is generally the preferred approach.


Asides related to the comment thread above:

  • In order to use Task, you need using System.Threading.Tasks;
  • In order to use Thread, you need using System.Threading;
  • Method names in C# are traditionally capitalized: WaitThen
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading