0

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);
            }
        }
    }
DaggeJ
  • 2,094
  • 1
  • 10
  • 22
Yori
  • 11
  • 2
  • You need to use Dispatcher.Invoke, just google it – Sandris B Apr 16 '20 at 09:34
  • 1
    You can only update the label on the GUI thread. – Sean Apr 16 '20 at 09:35
  • @SandrisB Thank you for your anwser. However, I don't really get it how to implement this in my code. Could you please help me? I haven't got much knowlegde besides just fairly simple programming yet. – Yori Apr 16 '20 at 10:41
  • 1
    Your current thread( UI thread) is responsible for managing the UI components, you then spawn a new thread that will be responsible for another operation. Now you want to update your UI with some data (held in the other thread operation, you have to request this information from the thread and pass it to the UI thread) you can use a Dispatcher, you cannot access data across threads directly. I would encourage you to read about Task – Harry Apr 16 '20 at 10:52
  • I kind of figured it out now. Thank you for your help – Yori Apr 16 '20 at 11:32

0 Answers0