2

I couldn't find an answer for this:

"Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on."

This is my code:

        private void buttonStart_Click(object sender, EventArgs e)
        {
            ClassCopy cb = new ClassCopy();
            cb.startCopy(textBoxSrc.Text, textBoxDest.Text, true);

            th = new Thread(loading);
            th.Start();

        }

        private loading()
        {
            for (int i = 0; i < 100; i++)
            {
                if (progressBar1.InvokeRequired)
                    progressBar1.Invoke(new Action(loading));
                else
                    progressBar1.Value = i;
            }
        }
terrybozzio
  • 4,424
  • 1
  • 19
  • 25
Ers313
  • 51
  • 1
  • 1
  • 3

2 Answers2

1

this simple change will do:

        private void loading()
        {
            for (int i = 0; i < 100; i++)
            {
                if (progressBar1.InvokeRequired)
                    progressBar1.Invoke(new Action(loading));
                else
                    progressBar1.Value = i;
            }
        }
terrybozzio
  • 4,424
  • 1
  • 19
  • 25
  • its working, but only when the copy is done, not during it – Ers313 Aug 26 '13 at 13:43
  • ahhhh by your edit i now think that what you are trying is see the update of the copy operation,for that the best aproach is the backgroundworker....try this to start - http://msdn.microsoft.com/en-us/library/vstudio/ywkkz4s1(v=vs.100).aspx ... also check this for more insight - http://www.dotnetperls.com/backgroundworker – terrybozzio Aug 26 '13 at 13:48
  • this is also about backgroundworker more detailed - http://www.dreamincode.net/forums/topic/112547-using-the-backgroundworker-in-c%23/ – terrybozzio Aug 26 '13 at 13:53
0

it's really just to do

private delegate void EventHandle();

private void loading()
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(10);
        Invoke(new EventHandle{progressBar1.Value++;})
    }
}

the sleep is so you'll see the change, otherwise it'll go from 0 to 100 in a millisecond

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70