Support Forums
Delay with loop - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Visual Basic and the .NET Framework (https://www.supportforums.net/forumdisplay.php?fid=19)
+---- Thread: Delay with loop (/showthread.php?tid=7184)



Delay with loop - macas5 - 05-19-2010

Hello it's me again. Now i am trying to make delay with loop. If i am using:
Code:
System.Threading.Thread.Sleep(500)
The program freezes until loop stops. Can i make somehow that program won't freeze when the loop is not finished? Thanks in advance Smile


RE: Delay with loop - thanasis2028 - 05-19-2010

Yes, you can use an onbect called backgroundworker:
1)Find the backgroundworker from the toolbox and add it to your form
2)Doubleclick the object added
3)In the event that appears add your code(the loop you want)
4)Now when you want to run this loop just use:
Code:
BackgroundWorker1.RunAsynchronousOperation() 'or something similar to it I don't remember it exactly
What did you just do with these actions? You now run the loop in a different thread. So when you use Threading.Thread.Sleep(500) only the thread of the loop freezes and not the entire application. However, notice there is one limitation: you can't edit any object in the form from a different thread. This means that a code like Textbox1.Text="Hello World" would cause a runtime error if it is used from within the BackgroundWorker.

Edit: You can also make your own threads without using the BackgoundWorker, which is much better, but a little more difficult for beginners. If you want to learn about it however, google VB.NET threading