Why is this C # timer code not working?

I need to disable the button for 1.5 seconds in one application that I am writing. An image is displayed, the user presses a button, and then another image is displayed. I need to make sure that the user does not click the button too quickly.

So, when the image is displayed, I call this function:

    //when a new image is displayed, start the timer and disable the 'done' button
    //for 1.5 seconds, to force people to stop pressing next so quickly
    System.Timers.Timer mTimer;
    void TimerStart() {
        Done.IsEnabled = false;

        mTimer = new System.Timers.Timer();
        mTimer.Interval = 1500;
        mTimer.Start();
        mTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimerEnd);
    }

TimerEnd code looks like this:

    void TimerEnd(object sender, EventArgs eArgs) {
        if (sender == mTimer){
            Done.IsEnabled = true;
            mTimer.Stop();
        }
    }

The line "Done.IsEnabled" hits, but the button is not re-enabled, and the timer does not stop shooting. What am I doing wrong here? If that matters, this is a WPF application.

+3
source share
4 answers

Use DispatcherTimer instead

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(someInterval);
timer.Tick += new EventHandler(someEventHandler);
timer.Start();

private void someEventHandler(Object sender, EventArgs args)
{
//some operations
//if you want this event handler executed for just once
// DispatcherTimer thisTimer = (DispatcherTimer)sender;
// thisTimer.Stop();
}
+7
source

, . , , , , .

+2

. winforms , Invoke , .

+1

WPF , , , UI, , . , .

BeginInvoke/EndInvoke , , Begin/End Invoke

There is also a SynchnornizationContext, which can be accessed by calling SynchronizationContext.Current. You will need to cache this before making a timer call, since SynchronizationContext.Current will be null in threads other than the UI.

This link also talks about it.

0
source

Source: https://habr.com/ru/post/1718341/


All Articles