W
W
wolfak2014-03-06 22:41:30
WPF
wolfak, 2014-03-06 22:41:30

How does Timer work in WPF?

Good evening.
I can't figure out the timer in Visual Studio C# for Windows RT.
It is necessary to write a function that would run every 0.5 seconds and move the object by 1 step. (x++;).
How to implement such a timer?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Terminaft, 2014-03-07
@wolfak

In WPF, from what I've read, it's better to use DispatcherTimer (System.Threading namespace).
Roughly speaking,

private DispatcherTimer timer = null;
private int x;

private void timerStart () {
            timer = new DispatcherTimer();  // если надо, то в скобках указываем приоритет, например DispatcherPriority.Render
            timer.Tick += new EventHandler(timerTick);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
            timer.Start();
}

private void timerTick(object sender, EventArgs e)
{
            x++;
}

A
Alexander S, 2014-03-07
@FirstX

For general reference, in addition to the first answer, there are roughly 2 main types of timers:
1. System.Threading.Timer - Puts a task in the thread pool, so it is suitable for those cases when the task is running on a timer in the background. For example, your object changes the X parameter, but this is not visible on the form.
2. System.Windows.Forms.Timer (for WinForms) / System.Windows.Threading.DispatcherTimer (WPF and Silvelight) and System.UI.XAML.DispatcherTimerfor Win Store applications there are still - these are all analogues that cause the execution of the method in the same thread as it was called. Thanks to this, access to the elements of the graphical interface is provided, but at the same time it is better not to put complex computational logic here.

N
Nubzilo, 2015-03-06
@Nubzilo

I'm bringing up an old thread so I don't create a new one.
If some method working with the network is to be called in WPF (the computational logic is not large, but lengthy), after its work it must change the interface element. What is the best timer class to use?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question