问题描述
当用户执行某项操作(在这种情况下,在StackPanel上进行触摸)时,我需要启动某种计时器(可能是在WPF中工作时为DispatcherTimer),并且如果在一定的时间内再次发生另一次触摸,然后我会调用一个方法.您可能会猜到-这是实现双击功能.
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.
我假设实现此目标的最佳方法是使用线程(即子线程增加时间跨度,只要再次触摸StackPanel即可由主线程检查该时间跨度?)
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?)
谢谢
丹
推荐答案
您无需启动另一个线程即可执行此操作.
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:
private DateTime _lastTap;
public void TapHandler()
{
DateTime now = DateTime.UtcNow;
TimeSpan span = now - lastTap;
_lastTap = now;
if (span < TimeSpan.FromSeconds(1)) {...}
}
或者,按照@DannyVarod的建议,您可以使用Stopwatch
达到相同的结果(但计时更准确):
Alternatively, as suggested by @DannyVarod, you can use a Stopwatch
to achieve the same result (but with more accurate timing):
private Stopwatch _stopwatch = new Stopwatch();
public void TapHandler()
{
TimeSpan elapsed = _stopwatch.Elapsed;
_stopwatch.Restart();
if (elapsed < TimeSpan.FromSeconds(1)) {...}
}
这篇关于如何使用线程来“勾选"其他线程可以访问的计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!