Stop the execute of command if it execute more than 3 seconds

Is it possible to stop the execute of a command if it executes more than 3 seconds?
If the command executes successfully, prompt a "Command execute success"
If the command executes failed, prompt a "Command execute failed"?

eg
Private Sub Command1_Click()
Call NonStopLoop
'if it executes more than 3 seconds, stop it. This is just an example, and obviously it won't stop within 3 seconds.
End Sub

Private Sub NonStopLoop()
Dim i As Integer
Do While True
    i = 1
Loop
End Sub
LVL 9
william007Asked:
Who is Participating?
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
If you are working in VB6 then the answer is No.  You would need to put the code in Command1_Click() into a different thread which is difficult to do in VB6.  If the call you are making is a blocking call, then a Timer approach would not work because it won't fire until the blocking call returns.

If you are working in VB.Net then it is easy to make another thread and cancel it after a timeout period.
0
 
PreachDotNetCommented:
Put a timer in and set a module level variable called timeout.

Dim Timeout as boolean = false


Sub Command1_Click
Dim t As New System.Timers.Timer(3000)
AddHandler t.Elapsed, AddressOf TimerFired
Call NonStopLoop
End Sub


Private Sub NonStopLoop()
Dim i As Integer
Do While True And Not(Timeout)
    i = 1
Loop
End Sub


Public Sub TimerFired(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
   TimeOut = True
End Sub




0
 
PreachDotNetCommented:
Sorry Theres the return true or false bit

Private Function NonStopLoop() as boolean
Dim i As Integer
Do While True And Not(Timeout)
    i = 1
Loop
Return Timeout
End Sub
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
william007Author Commented:
Thanks preachDotNet,

Can we assume that the NonStopLoop is a API function, and we can't change the code of it,
is it possible to interfere to command execution just in Command1_Click?
0
 
PreachDotNetCommented:
0
 
william007Author Commented:
Thanks, this is a general question,
I have post my real problem here,
http://www.experts-exchange.com/Programming/Programming_Languages/Visual_Basic/Q_21785775.html
Since if the remote server doesn't exist, the problem line will run forever, I wish to do something to let it time out for 3 seconds,
but now seems like I need to change my strategy.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.