-1

I am trying to use DispatcherTimer for multiple elements (visual, moving stackpanel)

It is possible to call the same DispatcherTimer_Tick for multiple elements? and all of them to move at the same time, but using a loop? And also how should I delay the dispatcher timer to create a new troop after a period of time?

for the moment I've dont something like this

for (int i = 1; i < 3; i++)
{
    dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
    index = i;
    FirstTroop(i);
    dispatcherTimer.Start();
}     
Bizhan
  • 16,157
  • 9
  • 63
  • 101

1 Answers1

1

It is possible to call the same DispatcherTimer_Tick for multiple elements?

Yes you can call dispatcherTimer_Tick(null, null) anywhere in your code. But it is recommended to leave the event handler for only handling tick events and instead call a more meaningful method for this purpose. like a SpawnTroop:

dispatcherTimer_Tick(object sender, EventArgs e)
{
    SpawnFirstTroop();
}

and all of them to move at the same time, but using a loop?

So you need to call dispatcherTimer_Tick inside a loop.

void Start()
{
    dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = TimeSpan.FromMilliseconds(1000);
    dispatcherTimer.Start();
}

dispatcherTimer_Tick(object sender, EventArgs e)
{
    for (int i = 1; i < 3; i++)
    {
        SpawnTroop(i);
    }  
}

And also how should I delay the dispatcher timer to create a new troop after a period of time?

According to MSDN:

If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.

There are multiple solutions for this:

  1. You can't use a Thread.Sleep with dispatcherTimer_Tick. But you can use Thread.Sleep with a Timer to delay inside timer's tick event handler.

  2. You can write more code for your dispatcherTimer to enable two intervals (like a simple integer counter withing the event handler). this approach is not recommended.

  3. You can use two dispatcher timers, one for queuing/requesting new objects, one for creating/showing them.

Bizhan
  • 16,157
  • 9
  • 63
  • 101
  • Thank your very much sir, I managed to do something like this on my own, but anyway thank you for your time :) I will try to read again from MSDN documentation. – user9368565 Jun 03 '18 at 16:46