Link to home
Start Free TrialLog in
Avatar of Desired_Username
Desired_Username

asked on

Repeating a task every few minutes

Im trying to process an event every x minutes after a button has been pressed in a windows form.  The current way im doing it uses a loop which shows the form as not responding after a few minutes.

Help as soon as possible please this has to be handed in soon



//Button press
        private void button2_Click(object sender, EventArgs e)
        {
                DoProcess();
                button2.Enabled = false;
        }
 
        private void DoProcess()
        {
            for(int a = 0; ;a++)
            {
                ////do the stuff here...... and min window
                this.WindowState = FormWindowState.Minimized;
                Thread.Sleep(40000);
            }
        }

Open in new window

Avatar of Babycorn-Starfish
Babycorn-Starfish
Flag of United States of America image

Hi,

i'd either kick off DoProcess in a separate thread, or see whether DoEvents has any impact on your form response problem.
Why not use a timer to "do the stuff"?
If doing "the stuff" is processor intensive, then do it in a backgroundworker thread.
ASKER CERTIFIED SOLUTION
Avatar of anmalaver
anmalaver

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Desired_Username
Desired_Username

ASKER

its not processor intensive no, my problem is that the process needs to be triggered when the button is hit.  But at the minute its entering DoProcess and getting stuck in my loop causing my form to crash.
You should have a flag to avoid that task can be invoked twice. You set it if it's clear, when you begin the process and clear again at finish.
You should not call Thread.Sleep for 40 seconds in your code.  If the thing you are processing is on the same thread then it will appear to be deadlocked.

Create a 5 minute timer (5 minutes = 300,000 milliseconds), but only start the timer when the button is clicked.  Call DoProcess in the timer event.