0

I've tried multiple variations of this, but none of them seem to work. Any ideas?

private void button11_Click(object sender, EventArgs e)
{
    // Code that runs on application startup
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.AutoReset = false;
  
    timer.Interval =1000;
    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    timer.Start();
}

void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    masu();
}

public void masu()
{
    int speed = 20;
    label3.Text = speed.ToString();
}

tips:+ $exception {"Invalid inter-thread operation: access the control "label3" from the thread that did not create it."} System.InvalidOperationException

Tim
  • 5,435
  • 7
  • 42
  • 62
huaye sun
  • 17
  • 6
  • 1
    i believe the timer must be a control of your form, _not_ a local variable. but that's just a wild guess; haven't done any UI dev in years – Franz Gleichmann Dec 08 '20 at 16:43
  • 7
    You shouldn't be using a `System.Timers.Timer` together with winforms, it uses threads, and you can't access controls on a form from a different thread than the one owning the form. Use the native timer for winforms instead. – Lasse V. Karlsen Dec 08 '20 at 16:45
  • 2
    You need to use [`System.Windows.Forms.Timer`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.timer?view=net-5.0) This gets a call back on the windows message pump. – Igor Dec 08 '20 at 16:46
  • 3
    @Lasse "shouldn't use System.Timers.Timer together with winforms" is a strong statement. I would say one shouldn't use that class if the main purpose is to update UI controls. There are, however, valid cases where `Timers.Timer` is to be used with WinForms. – 41686d6564 stands w. Palestine Dec 08 '20 at 16:53
  • @41686d6564 Agreed, good clarification. – Lasse V. Karlsen Dec 09 '20 at 09:16

0 Answers0