Activating button-reading outside of a timer cycle. RRS feed

  • Question

  • Hopefully the title isn't too confusing...

    I've got some code with the 'main' program running in a Timer_Tick cycle.  However, I want to have the option to turn off the timer and run that code in a loop that doesn't have to wait on the timer tick.  I'm expecting that this will result in more iterations through the loop in the same amount of time.

    However, when the user activates that loop, the program freezes.  It isn't using up all my system resources and isn't affecting any other programs running at the time. 

    Here is what the code does:

    When started by the user clicking a button, it first disables the Timer.
    Then it goes into a while loop that should run until the user clicks the same button on the GUI. 
    Inside the while loop, it runs the body of the program.

    After the while loop, the Timer is re-enabled and the program returns to the normal Timer_Tick operation.

    I need to be able to process exceptions from the buttons being clicked during that while loop.  I think it may have to do with using WndProc but I'm not sure exactly how.
    Friday, February 8, 2008 8:34 PM


  • Form events, like button clicks, run on the same processing thread as the GUI painting code.  This means if an event gets stuck processing a loop, no other events (like paints or clicks) can be processed and the program appears to lock up.  You can mitigate this somewhat by calling Application.DoEvents() inside the loop, but has a variety of other issues.

    The recommended approach is to run the intensive code in a BackgroundWorker object, and using a standard timer to monitor its progress.  The backround worker runs on a separate thread, so the form interactivity is not lost.  This also means that thread-safe approaches to objects and variables available to both threads is required.  It works really well, though Smile

    -Ryan / Kardax
    Friday, February 8, 2008 8:56 PM