延迟调度调用? [英] Delayed Dispatch Invoke?

查看:167
本文介绍了延迟调度调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,由于在该界面的更新有时我有一个短暂的延迟后执行动作的复杂性。

In WPF due to the intricacies on how the interface is updated I sometimes have to perform actions after a short delay.

目前我在做这个简单的方式:

Currently I'm doing this simply by:

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

不过,这既是一个有点难看,也许太多的开销,每次创建一个新的计时器(?) 什么是最好的,从性能的角度来看这样做,也就是执行最迅速?什么是重写上述code到类似好办法:

But it's both a bit ugly and perhaps too much overhead to create a new timer each time (?) What's the best from a performance standpoint to do it, ie execute most promptly? And what's good way to rewrite the above code into something like:

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

如果时间跨度是延迟,感谢您的任何输入:)

Where Timespan is the delay, Thanks for any input :)

推荐答案

我不会的假设的是, DispatcherTimer 是重量级的。 ..为什么不只是写在调度,它允许你使用你想要的语法,并使用 DispatcherTimer 在后台?我个人把它叫做 DelayInvoke ,而不是的BeginInvoke ,虽然...和我还修复它总是使用动作,而不是任意的代表...这将使它更容易使用的lambda EX pressions:

I wouldn't assume that the DispatcherTimer is heavy-weight... why not just write an extension method on Dispatcher which allows you to use the syntax you want, and uses a DispatcherTimer in the background? I would personally call it DelayInvoke rather than BeginInvoke though... and I'd also fix it to always use Action rather than an arbitrary delegate... that will make it easier to use lambda expressions:

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

(我倾向于认为这是更具可读性,如果匿名函数被用作一个方法调用的最后一个参数,但是这只是一个个人preference。)

(I tend to find it's more readable if anonymous functions are used as the final argument in a method call, but that's just a personal preference.)

既然你很可能希望使用毫秒的大部分时间,你可以有另一种辅助方法,也:

Given that you'll quite possibly want to use milliseconds most of the time, you could have another helper method too:

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

另一种尝试仅仅是使用现有的的BeginInvoke 的方法,但有一个非常低优先级,所以在一切已经完成了你的代表将只被调用。不知道你的情况的细节,很难知道这是否会工作或没有 - 但它是值得一试。

Another alternative to try is merely to use the existing BeginInvoke method but with a very low priority, so your delegate will only be invoked after everything else has finished. Without knowing the details of your situation, it's hard to know whether that'll work or not - but it's worth trying.

这篇关于延迟调度调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆