I was experimenting with Threads in Visual C# 2019, and I did so by creating a new Thread
that would change a label's text every second. However, the program stopped with the notification:
"It is not allowed to perform an operation via different threads; there was gained access to label1 via another thread then the one in which is was created"
Could anyone tell me what I'm doing wrong, and why?
public partial class Form1 : Form
// the other part is auto-generated code from visual studo. In there, label1 and button1 are defined.
{
Thread animatie;
bool test = true;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
animatie = new Thread(this.run);
animatie.Start();
}
private void run()
{
while (true)
{
if (test)
{
test = false;
label1.Text = "Lol";
}
else
{
test = true;
label1.Text = "Surprise";
}
Thread.Sleep(1000);
}
}
}