Jitendra Jadav
Jitendra Jadav

Reputation: 923

How I can set DispatcherTimer into the for loop

I am using wpf DispatcherTimer and I want ot use it into the for loop how i can use it..

my code is here..

        DispatcherTimer timer = new DispatcherTimer();

        timer.Tick += (s, e) =>
        {
            for (i = 0; i < 10; i++)
            {
                obsValue.Add(new Entities(i));
                timer.Interval = TimeSpan.FromSeconds(30);
                timer.Start();
            }
        };

Thanks....

Upvotes: 2

Views: 2913

Answers (2)

decyclone
decyclone

Reputation: 30840

When you start a timer with Interval set to 30 seconds, its Tick event will be raised every 30 seconds.

Now, what I understand from your question is you want to add a record every 30 seconds.

Here is what you can do. Note that it does not require a for loop but you still need to maintain current index. To do that, you can use a private field or a local variable with lambda.

Example:

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(30);
    
    Int32 index = 0, maxValue = 10;

    timer.Tick += (s, e) =>
    {                
        obsValue.Add(new Entities(index));
        index ++; // increment index

        // Stop if this event has been raised max number of times
        if(index > maxValue) timer.Stop();
    };

    timer.Start();

Upvotes: 3

ColinE
ColinE

Reputation: 70160

I think you misunderstand how the DispatcherTimer works. Once you invoke Start(), the Tick event will be fired each time the Interval has been reached, i.e. you start it and it ticks repeatedly. Your code should look like this instead:

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(30);
    timer.Start();

    timer.Tick += (s, e) =>
    {
        for (i = 0; i < 10; i++)
        {
            obsValue.Add(new Entities(i));
        }
    };

This will add 10 new Entities, every 30 seconds.

Upvotes: 1

Related Questions