How can I use threads to tick the timer to access other threads?

When the user does something (touch the StackPanel, in this case), I need to start some kind of timer (maybe DispatcherTimer, since I work in WPF), and if another touch happens again within a certain amount then I will call the method. As you can probably guess, this is a double-touch function.

I guess the best way to achieve this is to use threads (i.e., a child thread to increase the time that can be checked by the main thread by touching the StackPanel again?)

Thanks,

Dan

+2
source share
2 answers

You do not need to start another thread to do this.

Just take the time stamp when the first click occurred, and use it. Then you can calculate the time span 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)) {...} } 

Alternatively, as @DannyVarod suggested, you can use Stopwatch to achieve the same result (but with a more accurate time):

 private Stopwatch _stopwatch = new Stopwatch(); public void TapHandler() { TimeSpan elapsed = _stopwatch.Elapsed; _stopwatch.Restart(); if (elapsed < TimeSpan.FromSeconds(1)) {...} } 
+6
source

It is best to stick with DispatcherTimer , as you first pointed out, as this ensures that you do not need to sort the streams by tick. If you explicitly need accurate and / or background threads, see the System.Timers.Timer Class and System.Threading.Timer Class.

Sample code that distinguishes between single and double clicks can be found on MSDN (it depends on Windows Forms, but the principle is the same). Alternatively, please see this example using DispatcherTimer taken from this previous question.

  private static DispatcherTimer clickTimer = new DispatcherTimer( TimeSpan.FromMilliseconds(SystemInformation.DoubleClickTime), DispatcherPriority.Background, mouseWaitTimer_Tick, Dispatcher.CurrentDispatcher); private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e) { // Stop the timer from ticking. myClickWaitTimer.Stop(); Trace.WriteLine("Double Click"); e.Handled = true; } private void Button_Click(object sender, RoutedEventArgs e) { myClickWaitTimer.Start(); } private static void mouseWaitTimer_Tick(object sender, EventArgs e) { myClickWaitTimer.Stop(); // Handle Single Click Actions Trace.WriteLine("Single Click"); } 
+1
source

Source: https://habr.com/ru/post/1392895/


All Articles