0

So every 5 seconds the myTimer2 function gets executed. I'm trying to display the date and time when the function gets executed. Unfortunately, I'm getting System.InvalidOperationException error

"Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on"

    public UpdateForm2()
    {
        InitializeComponent();

        Timer x = new Timer(5000);
        x.AutoReset = true;
        x.Elapsed += new System.Timers.ElapsedEventHandler(myTimer2);
        x.Start();
    }

    public void myTimer2(object sender, System.Timers.ElapsedEventArgs e)
    {
        // Getting error on this line.
        textBox1.Text = "The textbox has been updated on " + DateTime.Now.ToString("HH:mm:ss tt") + Environment.NewLine;
    }
  • UI changes must be invoked on the main UI thread. See https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the –  Mar 15 '21 at 20:05
  • Is this Windows Forms? Then better use [System.Windows.Forms.Timer](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.timer) – Klaus Gütter Mar 15 '21 at 20:21

1 Answers1

0

You can use invoke.

public UpdateForm2()
{
    InitializeComponent();

    Timer x = new Timer(5000);
    x.AutoReset = true;
    x.Elapsed += new System.Timers.ElapsedEventHandler(myTimer2);
    x.Start();
}

public void myTimer2(object sender, System.Timers.ElapsedEventArgs e)
{
    
     this.Invoke(new MethodInvoker(delegate {
            textBox1.Text = "The textbox has been updated on " + DateTime.Now.ToString("HH:mm:ss tt") + Environment.NewLine;
        }));
        
  
}
psy
  • 48
  • 5