Waiting in vb2008 / vb.net - vb.net

I am a VB6 coder and I'm making the move to VB8 / VB.NET
I know how to wait in VB6, but my problem is that I don't know how to wait in VB8/VB.NET. I have a TextBox called textbox2 that contains the number of seconds I want to wait. I used to use wait 60 in VB6, but of course VB2008 is different.
Can anyone help me to do this?

I know this is an old question, but I thought there were so many conflicting answers and I thought the solution I use is simple and straightforward enough.
Also, I wrote this when I switched from VB6 to .net, for the same reason as OP.
Private Sub Wait(ByVal seconds As Long)
Dim dtEndTime As DateTime = DateTime.Now.AddSeconds(seconds)
While DateTime.Now < dtEndTime
Application.DoEvents()
End While
End Sub

Use this do that your UI does not hang.
For i = 1 to 300
threading.thread.sleep(i * 1000)
application.doevents
next

[edit: I re-read the question and see it was specifically asking about a TextBox named textbox2 so I've updated the answer to reflect that.]
Well, I think one answer would be to use:
System.Threading.Thread.Sleep(Int32.Parse(textbox2.Text) * 1000);
if your text box contains the number of seconds to wait. However if you aren't in a background thread, this will hang your application up for the amount of time you are waiting.
You could also do something like:
Dim StartTime As DateTime
StartTime = DateTime.Now
While (DateTime.Now - StartTime) < TimeSpan.FromSeconds(Int32.Parse(textbox2.Text))
System.Threading.Thread.Sleep(500)
Application.DoEvents()
End While
which would not hang up the UI while you wait. (Also, you could use Convert.Int32(textbox2.Text) to convert the data in the textbox.)
Oh, and in certain cases, another way you can avoid the issues with the UI locking up would be do implement a timer callback instead. (see http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx for some more detail.) To do this, you
do whatever processing you need to do before the pause
create a function that picks up processing where you left off
create a timer that calls your function afterward
Code:
Public Class MyClass
Public MyTimer As System.Timers.Timer
Public Sub OnWaitCompleted(source As Object, e As ElapsedEventArgs)
MyTimer.Stop()
MyTimer = Nothing
DoSecondPartOfProcessing()
End Sub
Public Sub DoFirstPartOfProcessing()
' do what you need to do before the wait
MyTimer = New System.Timers.Timer(Int32.Parse(textbox2.Text))
AddHandler MyTimer.Elapsed, AddressOf OnWaitCompleted
MyTimer.Start()
End Sub
Public Sub DoSecondPartOfProcessing()
' do what you need to do after the wait
End Sub
End Class

try to use a timer
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim interval As Integer = 0
If Integer.TryParse(Me.TextBox2.Text, interval) Then
Timer1.Enabled = True
Timer1.Interval = interval
Timer1.Start
End If
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
'your code here
End Sub
In the 'event of the timer ticks then implements the logic to invoke the method Timer.Stop (), but this depends on what you do.
Regards.

Use Thread.Sleep:
Thread.Sleep(60000)
Update, following comment:
To retrieve and convert the value of the text box use:
Dim sleepValue As Integer = Integer.Parse(textbox2.Text)
This will throw an exception if the value cannot be converted.

I don't know why do you want it and and why you don't use threads, but this sleep function act similar wait in vb6:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
MsgBox("begin")
Sleep(2000)
MsgBox("end")
End Sub

Related

VB: Repeat the function evey x minutes?

I'm working with visual basic express 2010 to create a very simple application.
I know this is basic stuff but i need to know how to repeat the same function every X minute while the application is being left open.
This is all my code:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
My.Computer.Network.DownloadFile(
"http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
End Sub
End Class
could someone please advise on this issue?
EDIT:
This is my entire code now:
Public Class Form1
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
My.Computer.Network.DownloadFile(
"http://new.tse.ir/en/json/MarketWatch/enMarketWatch_1.xls", "C:/temp/enMarketWatch_1.xls", "", "", False, 60, True)
End Sub
End Class
in the properties panel of the timer, I set the Enabled to true and Interval to 60000.
when i run this code, I get file downloaded but 1 second later, the file gets deleted automatically and an error pops up in the visual basic saying the operation has timed out
I tried to change the directory and still happening.
any advise would be appreciated.
Add a timer to your form in the graphical designer.
Double click the timer to generate its tick event handler code in the code window.
Move the code you want to repeat into a sub
Private Sub DownloadFile()
My.Computer.Network.DownloadFile("http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
End Sub
Add the command below into your timer tick event handler
DownloadFile()
Change your form.load event to
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DownloadFile()
Timer1.Interval = x ' where x is the number of minutes*60000 because there are 60000 ticks in a minute
Timer1.Enabled = True
End Sub
The reason I've put your code into a separate sub is so that it is easily reusable in both the form.load handler and the timer.tick handler without having to write it again, and if in the future you need to change, for example the file path, you only need to remember to change it once.
Also I should add that, in the form.load handler I have included the DownloadFile method because, when the timer is enabled, it won't generate a tick until the interval has elapsed. Not at the beginning when the timer is enabled.
Also - as Plutonix suggested in comments below - If it is possible that the file to be downloaded will take longer to download than the length of the timer interval you should disable the timer in the DownloadFile sub and enable it again at the end of the sub. Like so :-
Private Sub DownloadFile()
Timer1.Enabled = False
My.Computer.Network.DownloadFile("http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
Timer1.Enabled = True
End Sub

How to add programatically timer and other controls with source code VB.net

I want to specify in a text field how many timers I want to add to my form and specify the code that should be into the timer.
For instance: My textbox says "2" and then I click a button and it creates two timers and adds a specific source code for both timers.
I have tried different codes and while they worked, I wasn't able to specify the number of controls on a form to create.
How can I achieve this efficiently?
Thanks
Just to create one timer
Public Class Form1
private _timer as Windows.Forms.Timer
...
Public Sub New()
...
_timer = New Timer(Me)
_timer.Interval = 1000 'Timer will trigger one second after start
AddHandler _timer.tick, AddressOf Timer_tick 'Timer will call this sub when done
End Sub
Sub Button_click(sender as Object, e as EventArgs)
_timer.Start() 'Start the timer
...
End Sub
Private Sub Timer_tick(sender as Object, e as EventArgs)
MessageBox.Show("Timerrr!!")
End Sub
...
End Class
Now if you want to create more than one timer, you can use an array of Timer.
In this case, I used a form conatining a NumericUpDown controll element, a button and a label, plus two labels which only contain text.See this picture
To create the timers, I use the function add_timers(timercount), which looks like this:
Function add_timers(timercount As Integer)
'Using a loop to creat <timercount> timers
For g As Integer = 1 To timercount
'Creating new timer 't'
Dim t As New Timer()
'setting interval of t
t.Interval = 1000
'Enabling timer
t.Enabled = True
'Code which runs when t ticks
AddHandler t.Tick, AddressOf TimerTick
Next
End Function
This function gets called when Button1, the start button gets pressed. It uses NumericUpDown1.Value as the parameter for the function. The function uses a loop to create new timers t, sets their intervals and the code to run when they tick.
Unfourtunately, I didn't find a way to dynamically create code, so every timer performs the same action. Using arrays and loops in a clever way might enable you to use different value for each timer. To create code for the timer use a Sub:
Sub TimerTick(ByVal sender As Object, e As EventArgs)
'Add your code here
Label1.Text += 1
End Sub
The complete code I use is:
Public Class Form1
Function add_timers(timercount As Integer)
'Using a loop to creat <timercount> timers
For g As Integer = 1 To timercount
'Creating new timer 't'
Dim t As New Timer()
'setting interval of t
t.Interval = 1000
'Enabling timer
t.Enabled = True
'Code which runs when t ticks
AddHandler t.Tick, AddressOf TimerTick
Next
End Function
Sub TimerTick(ByVal sender As Object, e As EventArgs)
'Add your code here
Label1.Text += 1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
add_timers(NumericUpDown1.Value)
End Sub
End Class
Packing the timers into an array is possible, that way you can easily access each timer with its index. Serach for it on the internet, and if you then have no idea of how to do it, tell me in the comments.

[VB.NET]abort code/task after a time

Can i set time limit for a task or a code? for example if i want to show message boxes for 10 seconds and then stop or change the the message body ?
Yes, check out timers. There are three different kinds of timers:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
Which one will work best for you will depend entirely on your specific situation. Given the limited information you provided, I suspect that the easiest way to do what you need to do is to create your own message-box-like form and place a System.Windows.Forms.Timer component on the form (you can find it in the form designer's tool box). Have the form start the timer in its own Shown event. And then show the form using the ShowDialog method.
You can start a Thread and abort it when you want:
Dim t1 As New Threading.Thread(AddressOf MyMethod)
t1.Start()
Timer1.Start()
Private Sub MyMethod()
' Do what you want
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Enabled = False
t1.Abort()
End Sub

Long Running Process

I quickly wrote this little rinky-dink vb.net console app to demonstrate something to someone. When I got to looking at it I thought there must be a better way than eating up cycles by using
While True
...
End While
but I have no idea what it is. Any thoughts?
Module ControlExecutive
Private WithEvents MyTimer As New Timers.Timer
Sub Main()
MyTimer.Interval = 10000
Console.WriteLine("Start timer, interrupt every 10000 ms")
MyTimer.Start()
OuterLoop()
End Sub
Sub OuterLoop()
While True
'wait for timer interrupts
End While
End Sub
Sub HandleTimerInterrupt(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles MyTimer.Elapsed
Console.WriteLine(String.Format("Interrupt at {0}", DateTime.Now))
End Sub
End Module
Instead of (or inside) a loop for waiting, you should use System.Threading.Thread.Sleep(milliseconds). This will pause the thread without causing a CPU spike.

How do I call a function every x minutes in VB.NET?

How do I call a function every x minutes.
I assume I'd have to add a timer to the form?
here is a simple example:
Public Class SampleCallEveryXMinute
Private WithEvents xTimer as new System.Windows.Forms.Timer
Public Sub New(TickValue as integer)
xTimer = new System.Windows.Forms.Timer
xTimer.Interval = TickValue
End Sub
Public Sub StartTimer
xTimer.Start
End Sub
Public Sub StopTimer
xTimer.Stop
End Sub
Private Sub Timer_Tick Handles xTimer.Tick
SampleProcedure
End Sub
Private Sub SampleProcedure
'SomeCodesHERE
End Sub
End Class
USAGE:
Dim xSub as new SampleCallEveryXMinute(60000) ' 1000 ms = 1 sec so 60000 ms = 1 min
xSub.StartTimer
Yes, you could add a timer to the form, and set its interval to x*60000, where x is the number of minutes between calls.
Remember that the timer runs on the UI thread, so don't do anything intensive in the function. Also, if the UI thread is busy, the timer event will not fire until the UI thread finishes whatever event it is currently processing. If your function is going to be CPU-intensive, then consider having the timer start up a background worker
If you require a longer time period between function calls (ie, one thats too big for a timer interval) then you could have a timer function that fires every minute, and increments a counter until the desired amount of time has passed, before going on to call the function.
ALTERNATIVE 1
Here is good guide to use the Timer Control in VB.net.
The advantage is that you don't have to worry about modifying UI objects from non UI thread.
ALTERNATIVE 2
Another alternative is to spawn another thread and do the work and sleep the remaining x minutes.
The advantage here is that if your function doesn't touch UI objects your application will remain responsive to user input while the function is being called
Private Sub Form_Load()
_timer.Enabled = True
End Sub
Private Sub _timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
ListBox1.Items.Add(DateTime.Now.ToLongTimeString() + "," + DateTime.Now.ToLongDateString())
End Sub