Reputation: 153
So I have 3 labels and have to update all three of them at the same time using a random number until the user clicks a button that stops it.
This is what I have on my start button
private void start_Click(object sender, EventArgs e)
{
t1 = new Thread(new ThreadStart(FirstNumber));
t2 = new Thread(new ThreadStart(SecondNumber));
t3 = new Thread(new ThreadStart(ThirdNumber));
t1.Start();
t2.Start();
t3.Start();
}
This is what the methods that generate the random numbers look like
public void FirstNumber()
{
int j = r.Next(0, 50);
int k = r.Next(50, 100);
for (int i = j; i <= k; i++)
{
number1.Text = i.ToString();
Thread.Sleep(200);
}
}
When I debug I get the following error:
Cross-thread operation not valid: Control 'number2' accessed from a thread other than the thread it was created on.
I don't understand how I am meant to create controls for each thread, so any help is appreciated.
One more thing, will the user be able to click the stop button while the labels are being updated? Or do I need to add another thread that waits for the user input?
Thanks a lot!
Upvotes: 1
Views: 1677
Reputation: 615
For synchronous communication between threads in .NET is SynchronizationContext
// gui thread
var syncContext = System.Threading.SynchronizationContext.Current;
public void FirstNumber()
{
int j = r.Next(0, 50);
int k = r.Next(50, 100);
for (int i = j; i <= k; i++)
{
// Post or Send mth
syncContext.Post((o) =>
{
number1.Text = i.ToString();
});
Thread.Sleep(200);
}
}
Upvotes: 0
Reputation: 583
What you want is parallel activity. MS gives Parallel libraries , please go through below links
http://www.codeproject.com/Articles/152765/Task-Parallel-Library-1-of-n
http://www.codeproject.com/Articles/362996/Multi-core-programming-using-Task-Parallel-Library
Upvotes: 0
Reputation: 75306
You need set TextBox value only on UI Thread, not other threads, so you can use Control.Invoke
or Control.BeginInvoke
to execute delegate on UI Thread:
number1.BeginInvoke(new Action(() => { number1.Text = i.ToString(); }));
Upvotes: 6
Reputation: 26268
You can access UI only on UI thread. You can post things to UI thread through Dispatcher.BeginInvoke() method.
Upvotes: 1