定时器触发事件​​WPF(Timer to fire an event WPF)

2019-06-28 02:20发布

我在这里有一个项目,它的默认设置,通过MouseEnter事件发生的操作。 我的意思是,打开一个窗口,关闭,返回,不管,只发生在MouseEnter事件。

我只要求在3秒后,使事件火灾。 这意味着,用户将将鼠标上的控制,仅在3秒后的事件必须发生在窗口中的所有控件。

于是,我想到了一个全球性的定时器或相似的东西,直到计时器达到3,将返回false ...我认为,就是这样......

天啊,没有任何人知道我怎么能做出这样的事情?

谢谢!!

Answer 1:

可以定义一个类,将暴露出DelayedExecute接收动作来执行,并根据需要用于延迟执行创建计时器方法。 这将是这个样子:

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();
    }
}

然后,你可以这样调用:

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

要么

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


Answer 2:

我只是想补充一个简单的解决方案:

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

然后使用它,就像在这个其他答案



文章来源: Timer to fire an event WPF