Click here to Skip to main content
15,748,088 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a background worker which runs an infinite loop starting on form load.
I need help to get the index of the loop and show in a lable when the user clicks on a button.

here is my background worker which starts on form load.

C#
public Form1()
        {
            InitializeComponent();
           backgroundWorker1.RunWorkerAsync();

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            int i = 0;
            DateTime a;
          while ( i <= 1000)
            {
                a = DateTime.Now;
                if (i == 999)
                {
                    i = 0;

                }
                e.Result = a;

          }

        }
       private void btnShowIndex_Click(object sender, EventArgs e)
        {
           
        }
Posted

I strongly suggest you reading this MSDN page: "How to: Make Thread-Safe Calls to Windows Forms Controls"[^].
 
Share this answer
 
C#
while (i <= 1000) {
   // ...
   e.Result = a;
   backgroundWorker1.ReportProgress(i);
}

will allow you to pass the current index in your while loop to an appropriate event handler.

You have to create an handler for the ProgressChanged event to be catched:
C#
// During initialization:
backgroundWorker1.ReportProgress += backgroundWorker1_ProgressChanged;

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   // You will get the current index with
   int index = e.ProgressPercentage;
}
 
Share this answer
 
You have to decalre your counter in class level.
C#
public class Form1
{
int i =0;
public Form1()
        {
            InitializeComponent();
           backgroundWorker1.RunWorkerAsync();
 
        }
 
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
 
            
            DateTime a;
            while ( i <= 1000)
            {
                a = DateTime.Now;
                if (i == 999)
                {
                    i = 0;
 
                }
                e.Result = a;
 
          }
 
        }
       private void btnShowIndex_Click(object sender, EventArgs e)
        {
           label.Text = i.ToString();
        }
}
 
Share this answer
 
Comments
Linkz_G 24-Oct-13 11:08am    
Thanks a lot it worked for me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900