So I'm having a big problem on relocating my object in C# and this pops out when I try to run it (You may see some unknown words because it is on Serbian):
System.InvalidOperationException: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.SetBoundsCore(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified)
at System.Windows.Forms.Control.SetBounds(Int32 x, Int32 y, Int32 width, Int32 height, BoundsSpecified specified)
at System.Windows.Forms.Control.set_Location(Point value)
at WindowsFormsApp1.Form1.update() in G:\Soul Night fus\WindowsFormsApp1\WindowsFormsApp1\Form1.cs:line 136
void update()
{
var xloc = new Random();
var yloc = new Random();
int counter=0;
if (character.Location.X>= enemy.Location.X - 150&&character.Location.X <= enemy.Location.X + 150) {
if (character.Location.Y >= enemy.Location.Y - 150 && character.Location.Y <= enemy.Location.Y + 150)
{
if (character.Location.X < enemy.Location.X){
ex -= 5;
}
else{
ex += 5;
}
}
}
else{
ex += xloc.Next(-10, 10);
ey += yloc.Next(-10, 10);
if (enemy.Location.X > 1920){
ex -= 200;
}
if (enemy.Location.X < 0){
ex += 200;
}
if(enemy.Location.Y > 1080){
ey -= 200;
}
if (enemy.Location.Y < 0){
ey += 200;
}
}
try{
enemy.Location = new Point(ex, ey);
}
catch (Exception poruka){
MessageBox.Show(poruka.ToString());
System.Threading.Thread.Sleep(5000);
Application.Exit();
}
counter++;
Task.Delay(800).ContinueWith((task) => update());
}