Search code examples
c#wpftimertimespandispatchertimer

Timespan in a dispatcherTimer


I'm programing a WPF application in VS C# 2010 and I'm programming a simulation. This simulation can be either run automatically (by pressing the Auto button) or step by step (clicking the Step button). However, what I want to implement is a speed control.

I have designed a simple comboBox with 4 possible items (1,2,5,10), which represent the simulation speed. Here is the code I'm using:

private void button6_Click(object sender, EventArgs e)
    {
        int speed = Int32.Parse(comboBox1.Text.ToString());
        dispathcerTimer = new DispatcherTimer();
        dispathcerTimer.Tick +=new EventHandler(dispatcherTimer_Tick);
        dispathcerTimer.Interval = new TimeSpan(0, 0, 0, Convert.ToInt32(1000/speed));
        dispathcerTimer.Start();
    }

What this is supposed to do is to take the value selected in the comboBox and since TimeSpan does not accept double, just Int32, I must use the 4th parameter, miliseconds. I thought that doing 1000/speed would work but it does absolutely not, the time is even bigger. How can I change the time interval, for example, to reduce it from just 1 second (default at x1 Speed) to every 200 ms when the user selects the x5 Option?


Solution

  • You are using a wrong overload of TimeSpan, the fourth argument is actually for second (the first is for day). Try this simple static method TimeSpan.FromMilliseconds instead:

    dispathcerTimer.Interval = TimeSpan.FromMilliseconds(1000/speed);