C# Programming
02-05-2010, 07:13 AM
I'm trying to make a class that will simply put the progress bar in a loop (just to see how it works for learning purposes). I keep getting the following error though and I don't understand why.
error
Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.
here is the class code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms; // remove after testing used to show message boxes
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class thread
{
//Properties
private thread trd;
private ProgressBar _threadProgressBar;
public ProgressBar ThreadProgressBar
{
set { _threadProgressBar = value; }
get { return _threadProgressBar; }
}
public void startthread()
{
Thread trd = new Thread(new ThreadStart(this.ThreadTask));
trd.IsBackground = true;
trd.Start();
}
private void ThreadTask()
{
int stp;
int newval;
Random rnd = new Random();
while (true)
{
stp = ThreadProgressBar.Step * rnd.Next(-1, 2);
newval = ThreadProgressBar.Value + stp;
if (newval > ThreadProgressBar.Maximum)
newval = ThreadProgressBar.Maximum;
else if (newval < ThreadProgressBar.Minimum)
newval = ThreadProgressBar.Minimum;
ThreadProgressBar.Value = newval;
Thread.Sleep(100);
}
}
}
}
i'm calling it inside a windows form
with
public void callthread()
{
thread mythread = new thread();
mythread.ThreadProgressBar = progressBar1;
mythread.startthread();
}
thanks
error
Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.
here is the class code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms; // remove after testing used to show message boxes
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class thread
{
//Properties
private thread trd;
private ProgressBar _threadProgressBar;
public ProgressBar ThreadProgressBar
{
set { _threadProgressBar = value; }
get { return _threadProgressBar; }
}
public void startthread()
{
Thread trd = new Thread(new ThreadStart(this.ThreadTask));
trd.IsBackground = true;
trd.Start();
}
private void ThreadTask()
{
int stp;
int newval;
Random rnd = new Random();
while (true)
{
stp = ThreadProgressBar.Step * rnd.Next(-1, 2);
newval = ThreadProgressBar.Value + stp;
if (newval > ThreadProgressBar.Maximum)
newval = ThreadProgressBar.Maximum;
else if (newval < ThreadProgressBar.Minimum)
newval = ThreadProgressBar.Minimum;
ThreadProgressBar.Value = newval;
Thread.Sleep(100);
}
}
}
}
i'm calling it inside a windows form
with
public void callthread()
{
thread mythread = new thread();
mythread.ThreadProgressBar = progressBar1;
mythread.startthread();
}
thanks