Winforms equivalent of javascript setTimeout

davidsleeps picture davidsleeps · Dec 2, 2010 · Viewed 22.8k times · Source

Is there a simple solution/idea/strategy to create a setTimeout equivalent function in a WinForms app. I'm primarily a web developer but am not sure how I'd go about this in a WinForms App. Basically, I have a textbox, and after each keystroke I want to run a task to populate a list (like an auto-complete type thingy) but want to be able to cancel (e.g. clearTimeout) if the user keeps entering characters...

My only guess is to perhaps use a BackGroundWorker and make it sleep initially, and while it is sleeping, it could be cancelled, if the user stops entering keys and the sleep period ends, it then goes and runs the task etc

(i don't care if an example is C# or Vb.Net)

Answer

Robert picture Robert · Oct 16, 2014

I know this is an old question but an alternative solution would be to use Task.Delay(delay).ContinueWith((task) => { /* Code */ });.

Thread.Sleep vs Task.Delay?

or there is await Task.Delay(delay);

https://social.msdn.microsoft.com/Forums/vstudio/en-US/345f0402-3af0-4f96-a501-073674883ba3/building-an-async-settimeout-function?forum=csharpgeneral