Question

VB6 Program Appears Frozen While Running

Asked by: AJKConcepts

Hi all,

I seem to have the same problem with every VB6 app I write. While it is running through the loops of database code, the program appears frozen and I have to wait till it finishes. I have tried DoEvents, but it doesn't work. I have a text field that updates after each record is written and I just want to be able to see the textfield while the program is running. Is this not possible? Here is a snippet of code below, but it's actually doing this anytime any of my programs have any sort of loop. What am I missing? I've tried putting in a progress bar, and that doesn't work either.

DoEvents
        While Not EOF(1)
            Line Input #1, inputString
            tempArray = Split(inputString, vbTab)
             If UBound(tempArray) > 0 Then
                taxID = Replace(tempArray(2), "'", "")
                    If tempArray(10) <> "''" Then
                        faxNumber = Replace(tempArray(10), "'", "")
                        SQLstring = "UPDATE tblProvider SET FAX = '" & faxNumber & "' WHERE taxID = " & taxID
                        dbConnection.dbConnection.Execute SQLstring, , adExecuteNoRecords
                        frmMain.txtResult.Text = frmMain.txtResult.Text & "record " & taxID & " updated" & vbCrLf
                        frmMain.txtResult.Refresh
                    End If
                Else
                    '---write to the log file
                    objTxtStream.Write inputString & vbCrLf
                End If
        Wend

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-07-20 at 14:59:38ID22710868
Tags

vb6

,

program

Topic

Visual Basic Programming

Participating Experts
3
Points
500
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. DoEvents - Is there a work around?
    People have told me and told me not to use DoEvents because it is a resource hog and a sign of poor programming, but these people that tell me this never come up with an alternative to DoEvents for me. Now I ask... Do DoEvents Loop How would I accompl...
  2. Open File For Output - extra vbcrlf at EOF
    I am using the Open FIle For Output for writing a file. I am gathering the data from a Spreadsheet using Microsoft Office Web Components within my VB6 application. I have an export button on my form (cmdExport) and a Group with two options (optUnix and optWin). The options...
  3. Equivalent of VB6 DoEvents in C#
    What is the equivalent of VB6 DoEvents in C#? I have a calculation intensive loop in which I display a progress message in a textbox from time to time. But when I actually run the program, the textbox does not update immediately. Without programming a separate thread...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: zorvekPosted on 2007-07-20 at 15:02:31ID: 19535640

The best way to pause code execution is to provide a mechanism that gives the parent application such as Excel or Word opportunities to handle events as well as other operating system tasks. The routine below provides both and allows a pause of as little as a hundredth of a second.

Note that the declaration of the Sleep API function has to be placed above all other routines in the module.

[Begin Code Segment]

Public Declare Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)

Public Sub Pause( _
      ByVal Seconds As Single, _
      Optional ByVal PreventVBEvents As Boolean _
   )

' Pauses for the number of seconds specified. Seconds can be specified down to
' 1/100 of a second. The Windows Sleep routine is called during each cycle to
' give other applications time because, while DoEvents does the same, it does
' not wait and hence the VB loop code consumes more CPU cycles.

   Const MaxSystemSleepInterval = 25 ' milliseconds
   Const MinSystemSleepInterval = 1 ' milliseconds
   
   Dim ResumeTime As Double
   Dim Factor As Long
   Dim SleepDuration As Double
   
   Factor = CLng(24) * 60 * 60
   
   ResumeTime = Int(Now) + (Timer + Seconds) / Factor
   
   Do
      SleepDuration = (ResumeTime - (Int(Now) + Timer / Factor)) * Factor * 1000
      If SleepDuration > MaxSystemSleepInterval Then SleepDuration = MaxSystemSleepInterval
      If SleepDuration < MinSystemSleepInterval Then SleepDuration = MinSystemSleepInterval
      Sleep SleepDuration
      If Not PreventVBEvents Then DoEvents
   Loop Until Int(Now) + Timer / Factor >= ResumeTime
   
End Sub

[End Code Segment]

The DoEvents call is used to give the managed environment such as Excel or Word opportunities to handle events and do other work. But DoEvents only works within the managed environment and can still consume a considerable amount of resources without some other throttling mechanism. By also using the Windows Sleep API call the Windows operating system is given an opportunity to let other processes run. And, since the code is doing nothing but waiting, it is the appropriate thing to do.

Often the task involves waiting for an asynchronous task to complete such as a web query. To use the above routine while waiting for such a task to compete, two time durations are needed: the total amount of time to wait until it can be assumed that a failure has occurred in the other task, and the amount of time to wait between checks that the other task has completed. Determining how long to wait until giving up requires consideration of the longest possible time that the task could reasonably take and how long the user is willing to wait for that task to complete - wait too long and the user gets frustrated, don't wait long enough and the risk increases of falsely assuming an error occurred when it didn't. This duration is the more difficult to determine of the two. The second time, the duration between checks for completion, is easier to determine. This duration should be long enough to not consume unnecessary CPU cycles doing the check, but short enough to respond quickly when the status of the asynchronous task changes. A duration of between a quarter of a second and one second is usually reasonable. The sample code below illustrates how to wait for an asynchronous task to complete that usually finishes in less than 10 seconds.

   Dim TimeoutTime As Date
   TimeoutTime = Now() + TimeSerial(0, 0, 30) ' Allow 30 seconds for the asynchronous task to complete before assuming it failed
   Do While Now() < TimeoutTime And Not IsTaskComplete
      Pause 0.5 ' Pause half a second to allow the ashyncronous task (and the rest of the environment) to do work
   Loop

The above example uses a function named IsTaskComplete to determine if the asynchronous task completed. The function can do anything such as checking if a cell changed, checking if a control's property is set, or checking if a file exists.

Other techniques for pausing code execution and the problems with each are listed below. These should all be avoided in any well-designed application.

Wait Method (VBA only):

   Application.Wait Now + Time(0, 0, 10)

The Wait method suspends all application activity and may prevent other operations from getting processing time while Wait is in effect. However, background processes such as printing and recalculation continue. The net effect of pausing using the Wait method is to shut down the application (e.g. Excel) event handling and slow or stop other applications. This method does not allow any fractional seconds to be used.

Windows Sleep:

   Public Declare Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)
   Sleep 10000

Using the Sleep Windows API call is system friendly by allowing all other processes to get processing time but it effectively shuts down the parent application.

DoEvents Loop

   Do
      DoEvents
   Loop Until Now > TimeoutTime

Performing a DoEvents loop to pause gives the parent application a chance to handle events but, because there is no pause between DoEvents calls, virtually all available processing time is dedicated to the loop and nothing else which means this is not a good way to pause code execution. This method does not allow any fractional seconds to be used.

Basic Loop without DoEvents

   Do
   Loop Until Now > TimeoutTime

A tight loop without a DoEvents call effectively brings the workstation to a halt until the loop exits. This is the worst technique to pause code execution. This method does not allow any fractional seconds to be used.

There are other, more sophisticated, techniques that monitor event queues and other system resources but the net result is the same as a simple loop with both a DoEvents and a Sleep. As long as some other throttling mechanism is used such as the Windows Sleep function, DoEvents will consume very little resources as all it does is look for any pending events and then either process those events or return immediately to the caller.

Kevin

 

by: zorvekPosted on 2007-07-20 at 15:04:45ID: 19535661

Sorry, I posted too quickly...

You DON'T want to pause, you need to allow for VB and other apps to get some cycles. The above code will still work if you pass zero for the pause time.

Or, more simply, just put a DoEvents in the middle of the loop, not outside the loop.

Kevin

 

by: Idle_MindPosted on 2007-07-20 at 17:38:42ID: 19536481

A small pause INSIDE the loop may still be warranted as this prevents the loop from ramping CPU usage up to 100%...

 

by: Idle_MindPosted on 2007-07-20 at 17:41:37ID: 19536490

* So you need both:

-->   DoEvents to allow the app to process its message queue and remain responsive...including the ability to paint itself.
-->   Sleep() to throttle it back and not use 100% CPU cycles.  We're talking a small interval like 50 milliseconds.

Neither should be called for every iteration of the loop though.  You can either call them every XXX iterations or use a timing mechanism to call it every YYY milliseconds using methods no unlike the code above.


 

by: inthedarkPosted on 2007-07-21 at 07:30:14ID: 19539283

Idle_Mind's suggestion is good....it is a golden rule

When erever you start coding a Do or a For loopAs soon as you type the Do/For line you always put a doevents in the loop

Do Until Question=Answer
   ' then you start coding here
   DoEvents
Loop

Same for Do While and For Next loops, make it a habit.

zorvek: posted some good ideas and some bad ideas

This code is excellent and will use very very little CPU time about one second of CPU time very week on a continuous process..

Dim TimeoutTime As Date
   TimeoutTime = Now() + TimeSerial(0, 0, 30) ' Allow 30 seconds for the asynchronous task to complete before assuming it failed
   Do While Now() < TimeoutTime And Not IsTaskComplete
      Pause 0.5 ' Pause half a second to allow the ashyncronous task (and the rest of the environment) to do work
   Loop

But NEVER use Sleep for more then one second becuase if Windows decides to send you application a system message, the whole of windows will hand until the end og the sleep period.  Although Sleep is supposed to halt if there is a message I have seen examples where it does not.

1) Create a new project
2) add command1 to the form
3) pase the following code
4) hit run
5) click on sleep, then try to minimize the form

You will notice the whole system become slugissh


Option Explicit

Private Declare Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)

Private Sub Command1_Click()
Sleep 20000 ' twenty second
End Sub

Private Sub Form_Load()
Command1.Caption = "Sleep"
End Sub

Depending on the type of message that windows needs to send your app, if the message contains a pointer to a memory block, and your app is a servce, the whole PC will appear to die.

So a sleep of 1 second is tha max you should ever use....hope this helps:~)

ps I created my own version of Now which uses clock ticks and works about 50% faster than Now.

 

by: zorvekPosted on 2007-07-21 at 09:29:15ID: 19539861

>But NEVER use Sleep for more then one second...

And that's one of the reasons there is a built-in maximum Sleep duration of 25 milliseconds in my Pause routine. The whole purpose of the Pause routine was to combine the best of Sleep and DoEvents and overcome the limitations of using each in isolation while maximizing application AND Windows responsiveness.

As far as Sleep itself goes, anyone building Windows services that receives events with pointers to memory blocks should be well beyond using sleep for ANY significant duration of time. The ONLY reason to use Sleep with anything more than a few milliseconds is if the application really needs to be put to sleep AND no other process depends on it.

Kevin

 

by: inthedarkPosted on 2007-07-23 at 00:57:43ID: 19545648

zorvek the reaone why I thought that one of your sleep loos deserved praise becuase  it had no calculations within the loop. But the other one did.

Unfortunately any application can be subject to hanging the windows system. It is a feature of the way the windows sends system messages. Some messages need to have some meory allocated, in this case windows has to wait until the the message is received so it can destroy the memory that was allocated. But if you stick to very short pauses that is perfect.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...