0

I am trying to update a Label in a Thread. I have tried multiple different methods and still can't update my labels text here is my code

public form1()
{
    InitializeComponent();
    new Thread(SampleFunction).Start();
}
private void setLabel1TextSafe(string txt)
{
    if (label1.InvokeRequired)
    {
        label1.Invoke(new Action(() => label1.Text = txt));
        return;
    }
    label1.Text = txt;
}
public void AppendText(string value)
{
    label1.Text += value;
}
void SampleFunction()
{
    // Gets executed on a seperate thread and 
    // doesn't block the UI while sleeping
    for (int i = 0; i < 5; i++)
    {
        setLabel1TextSafe("Heya");
        Thread.Sleep(1000);
    }
}

There is no error being cast but the label text is not being changed or updated Anyone can help? Thank You

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Dal Ledg
  • 39
  • 6
  • Thank You For the Edit I was having problem with code blocks @reza-aghaei – Dal Ledg Nov 26 '15 at 20:19
  • You're welcome :) Your codes seems working. Do you have any other threads or `Thread.Sleep()` somewhere else in your form? – Reza Aghaei Nov 26 '15 at 20:26
  • 1
    Possible duplicate of [How to update the GUI from another thread in C#?](http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c) – Kif Nov 26 '15 at 20:36
  • 2
    why should ir be supposed to change, if you are always send the same value "Heya"? Try sending another value and see if it change – Sameh Deabes Nov 26 '15 at 21:39
  • Heya is just a test variable it should be changing from "Label1" to "heya" in the thread @Sameh – Dal Ledg Nov 27 '15 at 06:23
  • No I don't have any other Time.Sleep() but I'm using the mjpegprocessor.dll could that be it? @reza – Dal Ledg Nov 27 '15 at 06:25
  • You code works perfectly fine for me. I see the updated value in the label. You need to either create a [mcve] or delete this question. – Enigmativity Nov 28 '15 at 11:14
  • @SamehDeabes - I tried exactly that in my test. I did `setLabel1TextSafe("Heya" + i);` and I saw the label update as intended. This question is unanswerable until the OP provides code that replicates the issue. – Enigmativity Nov 28 '15 at 11:15

0 Answers0