Timer to fire an event WPF

2019-02-18 14:10发布

问题:

I have a project here and it has set by default that the actions occur by MouseEnter event. I mean, opening a Window, closing, returning, whatever, happens only by the MouseEnter event.

I was requested to make the event fire only after 3 seconds. That means that the user will place the mouse on the control and only after 3 seconds the event must happen for all the controls in the window.

So, I thought about a global timer or something alike, that will return false untill the timer reaches 3... I think that's the way...

Geez, does anybody knows how can I make such thing?

Thanks!!

回答1:

You can define a class that will expose a DelayedExecute method that receives an action to execute and creates timers as needed for the delayed execution. It would look something like this:

public static class DelayedExecutionService
{
    // We keep a static list of timers because if we only declare the timers
    // in the scope of the method, they might be garbage collected prematurely.
    private static IList<DispatcherTimer> timers = new List<DispatcherTimer>();

    public static void DelayedExecute(Action action, int delay = 3)
    {
        var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();

        // Add the timer to the list to avoid it being garbage collected
        // after we exit the scope of the method.
        timers.Add(dispatcherTimer);

        EventHandler handler = null;
        handler = (sender, e) =>
        {
            // Stop the timer so it won't keep executing every X seconds
            // and also avoid keeping the handler in memory.
            dispatcherTimer.Tick -= handler;
            dispatcherTimer.Stop();

            // The timer is no longer used and shouldn't be kept in memory.
            timers.Remove(dispatcherTimer);

            // Perform the action.
            action();
        };

        dispatcherTimer.Tick += handler;
        dispatcherTimer.Interval = TimeSpan.FromSeconds(delay);
        dispatcherTimer.Start();
    }
}

Then you can call it like this:

DelayedExecutionService.DelayedExecute(() => MessageBox.Show("Hello!"));

or

DelayedExecutionService.DelayedExecute(() => 
{
    DoSomething();
    DoSomethingElse();
});


回答2:

I just wanted to add a simpler solution:

public static void DelayedExecute(Action action, int delay = 3000)
{
    Task.Factory.StartNew(() => 
    {
        Thread.Sleep(delay);
        action();
    }
}

Then use it just like in this other answer