3

我在这里有一个项目,默认情况下,动作由 MouseEnter 事件发生。我的意思是,打开一个窗口、关闭、返回等等,都只发生在 MouseEnter 事件中。

我被要求仅在 3 秒后触发事件。这意味着用户将鼠标放在控件上,并且仅在 3 秒后,窗口中的所有控件都必须发生事件。

所以,我想到了一个全局计时器或类似的东西,它会返回 false 直到计时器达到 3 ......我认为就是这样......

Geez,有人知道我怎么能做这样的事情吗?

谢谢!!

4

2 回答 2

7

您可以定义一个类,该类将公开一个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();
});
于 2012-09-09T19:24:37.573 回答
1

我只是想添加一个更简单的解决方案:

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

然后就像在其他答案中一样使用它

于 2012-09-15T15:26:51.617 回答