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:
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.
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.
You can use two dispatcher timers, one for queuing/requesting new objects, one for creating/showing them.