代码之家  ›  专栏  ›  技术社区  ›  Homde

延迟调度调用?

  •  16
  • Homde  · 技术社区  · 15 年前

    在WPF中,由于接口更新的复杂性,我有时不得不在短暂的延迟后执行操作。

    目前,我的做法很简单:

            var dt = new DispatcherTimer(DispatcherPriority.Send);
            dt.Tick += (s, e) =>
            {
                dt.Stop();
                //DoStuff
            };
            dt.Interval = TimeSpan.FromMilliseconds(200);
            dt.Start();
    

    但是每次创建一个新的计时器都有点难看,而且可能开销太大(?)

            this.Dispatcher.BeginInvoke(new Action(delegate()
            {
                //DoStuff
            }), DispatcherPriority.Send,TimeSpan.FromMilliseconds(200));
    

    其中Timespan是延迟,感谢您的输入:)

    4 回复  |  直到 15 年前
        1
  •  12
  •   Jon Skeet    15 年前

    我不会的 假定 DispatcherTimer 很重。。。为什么不在上面写一个扩展方法呢 Dispatcher 定时器 DelayInvoke BeginInvoke 不过。。。我也会把它修好一直用 Action 而不是一个武断的代表。。。这将使lambda表达式的使用更加容易:

    Dispatcher.DelayInvoke(TimeSpan.FromMilliseconds(200), () => { ... 
    });
    

    (我倾向于发现,如果在方法调用中使用匿名函数作为最终参数,则可读性更高,但这只是个人偏好。)

    Dispatcher.DelayInvokeMillis(200, () => { ... 
    });
    

    另一种尝试的方法是仅仅使用现有的 方法,但优先级非常低,因此只有在完成其他所有操作后才会调用您的委托。如果不知道你的情况的细节,很难知道这是否有效-但值得一试。

        2
  •  10
  •   Anthony Hayward    11 年前

    .NET 4.5方式:

        public async void MyMethod()
        {
            await Task.Delay(20); 
            await Dispatcher.BeginInvoke((Action)DoStuff);
        }
    
        3
  •  2
  •   Rick Strahl    9 年前

    我用的是 Task.Delay() 把它包起来 Dispatcher.Delay() 扩展方法:

    public static class DispatcherExtensions
    {
    
        public static void Delay(this Dispatcher disp, int delayMs,
                                 Action<object> action, object parm = null)
        {
            var ignore = Task.Delay(delayMs).ContinueWith((t) =>
            {
                disp.Invoke(action, parm);
            });
        }
    
        public static void DelayWithPriority(this Dispatcher disp, int delayMs,
                          Action<object> action, object parm = null, 
                          DispatcherPriority priority = DispatcherPriority.ApplicationIdle)
        {
            var ignore = Task.Delay(delayMs).ContinueWith((t) =>
            {
                disp.BeginInvoke(action, priority, parm);
            });
    
        }
    
        public static async Task DelayAsync(this Dispatcher disp, int delayMs,
                          Action<object> action, object parm = null,
                          DispatcherPriority priority = DispatcherPriority.ApplicationIdle)
        {
            await Task.Delay(delayMs);
            await disp.BeginInvoke(action, priority, parm);
        }
    }
    

    那么叫这个:

    Dispatcher.Delay(4000, (win) =>
    {
         var window = win as MainWindow;
         window.ShowStatus(null, 0);
    },this);
    
        4
  •  0
  •   Govert    15 年前

    您可以从这里使用Paul Stowell的DelayBinding类: http://www.paulstovell.com/wpf-delaybinding

    使用此函数,可以绑定到类上的DependencyProperty,该类可以在属性更改时执行操作。绑定将管理延迟。 如果您有MVVM类型的设计,可能会特别好。

    推荐文章