Álvaro García
Álvaro García

Reputation: 19356

Why does the DispatcherTimer start immediatly instead of waiting until the interval arise?

I wanted to use a DispatcherTimer to decide if a click with mouse is click or double click. I am using the solution by mm8 in this thread.

My test code is this one:

DispatcherTimer _myTimer = new DispatcherTimer();

public Constructor()
{
    _myTimer.Interval = new TimeSpan(1000);
    _myTimer.Tick += OnOneClickTick;
}

private void OnPreviewMouseLeftButtonDownCommand(MouseButtonEventArgs e)
{
    try
    {
        if(e.ClickCount == 2)
        {
            _myTimer.Stop();
            string dummy = "";
        }
        else
        {
            _myTimer.Start();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("error");
    }
}

private void OnOneClickTick(object sender, System.EventArgs e)
{
    _myTimer.Stop();
    string dummy = "";
}

The idea is, when I click one time, start the timer, but don't execute yet, just wait a second click, if it doesn't happen, then run the itmer handler, if it is happen, stop the timer, so the timer it wouldn't be execute.

However, the timer handler is executed immediately when I start the timer in the click mouse event. I thought that the code of the timer handler will be execute after the interval is arise, after 1 second (1 second to have time to test if it works, later 250ms is a good interval).

Why is that?

Upvotes: 1

Views: 473

Answers (1)

Corentin Pane
Corentin Pane

Reputation: 4943

The constructor of TimeSpan that you are using is the one that takes a number of ticks as argument. So you are basically setting an interval of 1000 ticks, which is 0.0001s, so it seems that the callback is called immediately but that's not exactly the case.

You should use TimeSpan.FromMilliseconds instead.

Upvotes: 2

Related Questions