如何使用线程来“勾选”?一个可供其他线程访问的计时器?
当用户执行某些操作时(在本例中触摸 StackPanel),我需要启动某种计时器(可能是 DispatcherTimer,因为我在 WPF 中工作),如果在一定时间内再次发生另一次触摸,那么我会调用一个方法。您可能会猜到 - 这是为了实现双击功能。
我假设实现此目的的最佳方法是通过使用线程(即子线程来增加时间跨度,每当再次触摸 StackPanel 时主线程都可以检查该时间跨度?)
谢谢,
Dan
When the user does something (touch on a StackPanel, in this case), I need to begin a timer of some sort (probably DispatcherTimer as I'm working in WPF) and if another touch happens again within a certain amount of time then I'll call a method. As you can probably guess - this is to implement a double-tap functionality.
I'm assuming the best way to achieve this is through using threads (i.e. a child thread to increment a timespan which can be checked by the Main thread any time the StackPanel is touched again?)
Thanks,
Dan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要启动另一个线程来执行此操作。
只需获取第一次点击发生的时间戳并使用它即可。然后,您可以通过从当前时间减去该时间来计算时间跨度:
或者,按照@DannyVarod的建议,您可以使用秒表来获得相同的结果(但计时更准确):
You do not need to start another thread to do this.
Just take a timestamp of when the first tap happened and use this. You can then calculate the timespan by subtracting this time from the current time:
Alternatively, as suggested by @DannyVarod, you can use a
Stopwatch
to achieve the same result (but with more accurate timing):最好的方法是坚持使用 DispatcherTimer,正如您首先指出的那样,因为这将确保您不需要在滴答声上进行任何线程编组。如果您明确需要准确性和/或后台线程,请参阅 System.Timers.Timer 类和 System.Threading.Timer 类。
可以在 MSDN(Windows 窗体特定,但原理是相同的)。或者,请参阅使用 DispatcherTimer 的示例,取自上一个问题
The best way is to stick with
DispatcherTimer
as you first pointed out, as this will ensure you don't need to do any thread marshalling on tick. If you explictly need accuracy and/or background threads, please see theSystem.Timers.Timer
class andSystem.Threading.Timer
class.A code example which allows differentiation between Single and Double clicks can be found on MSDN (Windows Forms specific, however the principle is the same). Alternatively, please see this example using DispatcherTimer taken from this previous question