Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Timer and BackgroundWorker

Status
Not open for further replies.

kokon

Programmer
Apr 27, 2006
31
0
0
PL
Hi, After starting below code, the output I got is:
-------------
day
minute
day
minute,minute
day
minute,minute,minute
--------------
It should be:
--------------
day
minute,
day
minute
day
minute
--------------
I don`t knowo why the backgroud worker starts more then 1 time on each steps, is Background worker cancelletion working right?
Please help.

Code:
        private void Form1_Load(object sender, EventArgs e)
        {
          

            timer1.Interval = 3000;
            timer1.Tick += new EventHandler(DayTicker);
            timer1.Start();
        }
        
        public void DayTicker(object sender, EventArgs e)
        {
            timer1.Stop();
            if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync();
            if (backgroundWorker1.CancellationPending) return;
           
            richTextBox1.Text += "\n day   \n";

            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.DoWork += new DoWorkEventHandler(bw_DoWork_day);
            backgroundWorker1.RunWorkerAsync("test");
            backgroundWorker1.RunWorkerCompleted += bw_workerday_coplete;
            
        }

        public void bw_DoWork_day(object sender, DoWorkEventArgs e)
        {
            string w = "minute";
            e.Result = 1;

            e.Cancel = true;

            if (InvokeRequired)
                Invoke(new Change(OnChange), w);
        }

        public void bw_workerday_coplete(object sender, RunWorkerCompletedEventArgs e)
        {
           if (e.Error != null)
                MessageBox.Show("Worker exception: " + e.Error.ToString());
            else if (e.Cancelled)
            {
                timer1.Tick += new EventHandler(DayTicker);
                timer1.Start();
            }
         }

        private void OnChange(string w)
        {
            richTextBox1.Text += w + ",";
            Application.DoEvents();
        }

        private delegate void Change(string w);
    }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top