Reputation: 7377
I'm looking for a simple way to perform an action/method after a delay of n seconds. The thing I found a few examples but they seem overly complex for when on my last platform, iOS, it was just
[self performSelector:@selector(methodname) withDelay:3];
Any tips or code snippets would be much appreciated.
Upvotes: 1
Views: 2416
Reputation: 84744
You can also use Scheduler.Dispatcher
from Microsoft.Phone.Reactive
:
Scheduler.Dispatcher.Schedule(MethodName, TimeSpan.FromSeconds(5));
private void MethodName()
{
// This happens 5 seconds later (on the UI thread)
}
Upvotes: 5
Reputation: 1525
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += (s, e) =>
{
// do some very quick work here
// update the UI
StatusText.Text = DateTime.Now.Second.ToString();
};
timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
Note that what you're doing here is interrupting the UI thread, not really running anything on a separate thread. It's not suitable for anything long-running and cpu-intensive, but rather something where you need to execute on a regular interval. Clock UI updates are a perfect example.
Also Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.
For more information use this link
If you want to use Timer for the background task then use the System.Threading.Timer instead of DispatcherTimer
For more information use this link
Upvotes: 0
Reputation: 8126
DispatcherTimer DelayedTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromSeconds(5)
};
DelayedTimer.Tick += (s, e) =>
{
//perform action
DelayedTimer.Stop();
}
DelayedTimer.Start();
Upvotes: 4