Easy way to beat a method after a certain delay?

Is there an easy way to execute a method after a given delay, for example in iOS?

On an iPhone, I would do this:

[self performSelector:@selector(connectSensor) withObject:nil afterDelay:2.5];

Then he will pay the connectSensor method in the main thread (UI thread), which will be executed in 2.5 seconds. And since it is automatically assigned in the main thread, you do not need to worry about cross-threading issues. (There is also a version of performSelectorOnBackground )

So, how would I do it right in WP7?

I am currently doing this with a timer, but I'm not sure if this is a good solution.

  private Timer timer; private void DoSomethingAfterDaly() { // ... do something here timer = new Timer( (o) => Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.GoBack()), null, 2500, Timeout.Infinite); } 

How can this be encapsulated in an extension method, so I can just call this.Perform(MyMethod, null, 2500); ?

+7
source share
2 answers

You can use BackgroundWorker like this:

  private void Perform(Action myMethod, int delayInMilliseconds) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (s, e) => Thread.Sleep(delayInMilliseconds); worker.RunWorkerCompleted += (s, e) => myMethod.Invoke(); worker.RunWorkerAsync(); } 

A call to this method will look like this:

 this.Perform(() => MyMethod(), 2500); 

The background worker will start a sleeping thread from the user interface thread, so your application is free to perform other actions during the delay.

+11
source

You can use Reactive Extensions for WP7 to monitor the timer:

 Observable .Timer(TimeSpan.FromMilliseconds(2500)) .SubscribeOnDispatcher() .Subscribe(_ => { NavigationService.GoBack(); }); 

Given the brevity of this code, I don’t think you will gain much by creating an extension method for it. For more information on Reactive Extensions for WP7, look at this MSDN page .

+8
source

All Articles