Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-thread operation not valid using timer and 2 buttons

i got this problem...

What would be a good solution for this?

 private void button1_Click(object sender, EventArgs e)
    {
        aTimer.Enabled = true;
        button1.Enabled = false;

    }

    private void button2_Click(object sender, EventArgs e)
    {
        aTimer.Enabled = false;
    }

    private void timer_is_working(object source, ElapsedEventArgs e)
    {
        aTimer.Enabled = false;
        button1.Enabled = true;
    }

Thanks! Kind regards Daniel Ruescher

like image 504
rusky Avatar asked Aug 14 '26 17:08

rusky


2 Answers

So you did not make it clear, but based on the ElapsedEventArgs type it seems that timer_is_working is the Elapsed event of a System.Timers.Timer instance.

Be aware that the .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer: fires an event at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment.
  • System.Threading.Timer: executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment.
  • System.Windows.Forms.Timer: a Windows Forms component that fires an event at regular intervals. The component is designed for use in a single-threaded environment.
  • System.Web.UI.Timer: an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

If this is a Windows.Forms app, use a System.Windows.Forms.Timer instead (you find it in Toolbox/Components). Its Tick event is raised in the UI thread so can access your controls from there.

If you have a special reason to use the System.Timers.Timer (eg. precision), you must wrap your access into an Invoke call:

Invoke(new Action(() => { button1.Enabled = true; }));
like image 145
György Kőszeg Avatar answered Aug 16 '26 08:08

György Kőszeg


You can use Invoke to update UI by using UI thread.

Try this example

private void timer_is_working(object source, ElapsedEventArgs e)
{
    ExecuteSecure(() => aTimer.Enabled = false);        
    ExecuteSecure(() => button1.Enabled = true);
}

private void ExecuteSecure(Action action)
{
    if (InvokeRequired)
    {
        Invoke(new MethodInvoker(() =>
        {
            action();
        }));
    }
    else
    {
        action();
    }
}
like image 42
NASSER Avatar answered Aug 16 '26 07:08

NASSER



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!