3583

How can I use threading to 'tick' a timer to be accessed by other threads?

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

Answer1:

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)) {...} }

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)) {...} }

Answer2:

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 the System.Timers.Timer class and System.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

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"); }

Recommend

  • Maven (Eclipse plugin and mvn) not including main class with pom.xml setup
  • turning table rows into columns in mysql
  • UIDynamicItem with non-rectangular bounds
  • Firefox only runs the CSS animation once
  • Fast way to validate if all checkboxes are un-selected?
  • mysql: select query when the column that has condition on has NULL value
  • Customize dc.js date x-axis
  • Methods of creating a structured array
  • Google Map API v3 - Centre Map on Markers
  • printf, saying, getName setName
  • String Split sql function only returning first word in string
  • Muliple upload php script and store in mysql database
  • RavenDB indexing errors
  • Using Nested Table variables / Collections in SQL inside PL/SQL blocks
  • Extract zip entries to another Zip file
  • Eloquent update method change created_at timestamp
  • ActiveRecord query for a count of new users by day
  • Jetty Server not starting: Unable to establish loopback connection
  • Debugging ASP.NET on a built-in web server suddenly stops
  • Illegal mix of collations for operation for date/time comparison
  • output of program is not same as passed argument
  • Validaiting emails with Net.Mail MailAddress
  • sending/ receiving email in Java
  • Javascript + PHP Encryption with pidCrypt
  • Invalid access key error using credentials redeemed from an amazon open id token
  • Cannot Parse HTML Data Using Android / JSOUP
  • PHP: When would you need the self:: keyword?
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • python regex in pyparsing
  • Acquiring multiple attributes from .xml file in c#
  • JTable with a ScrollPane misbehaving
  • Getting Messege Twice Using IMvxMessenger
  • Android Google Maps API OnLocationChanged only called once
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • reshape alternating columns in less time and using less memory
  • How can i traverse a binary tree from right to left in java?
  • failed to connect to specific WiFi in android programmatically