I have Visual c# 2010 express installed, I Wanted to call a method that takes parameters using a thread, but during the execution of the method, the thread should stop, and I am supposed to see the impact on the form, and then the method should continue.
The operation is simply moving a Label
-that is generated from the code on the form_load
event- on the form.
I have used three different ways of calling Thread.sleep()
method, but each of them is either not suggested by the intellisense or causing an exception -for the last case, which I want to understand.
Why am I having this exception and what does it mean?.
Is there a better approach to follow?.
public Thread thr;
private void Form1_Load(object sender, EventArgs e)
{
Label os = (Label)this.Controls[0];
os.Text = "codeLB";
thr = new Thread(() => Beta(os,thr));
thr.Start();
}
public void Beta(Label os,Thread tr)
{
1. os.Location = new Point(os.Location.X + 10, os.Location.Y + 10);
while(os.Location.Y<=400)
{
this.Refresh();
//here I want to sleep the thread.
//tr.sleep(1000); doesn't work (not suggested)
//Thread.CurrentThread.sleep(1000); doesn't work (not suggested)
Thread.Sleep(1000); // it works but it causes an unhandled InvalidOperationException in line 1
"Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on."
os.Location = new Point(os.Location.X + 10, os.Location.Y + 10);
}
os.Location = new Point(0, 0);
}
Many thanks.