Easy way to excecute method after a given delay?

放肆的年华 提交于 2020-01-11 19:56:26

问题


Is there a easy way to perform a method after a given delay like in iOS out of the box?

On iPhone I would do this:

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

It will then schedule the method connectSensor on the main thread (UI thread) to be executed after 2,5 seconds. And because it is automatically scheduled on the main thread, you don't have to worry about cross thread issues. (There is also a performSelectorOnBackground version)

So how would I do this properly in WP7?

Currently I'm accomplishing 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 could this be encapsulated into an extension method so I can just call this.Perform(MyMethod, null, 2500); ?


回答1:


You can use a BackgroundWorker like so:

    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();
    }

The call into this method would look like this:

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

The background worker will run the sleep on a thread off of the UI thread so your application is free to do other things while the delay is occurring.




回答2:


You can use the Reactive Extensions for WP7 to observe on a timer:

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

Given the brevity of this code, I don't think you'd gain much by creating an extension method for it :) For more information about the Reactive Extensions for WP7, take a look at this MSDN page .



来源:https://stackoverflow.com/questions/4726239/easy-way-to-excecute-method-after-a-given-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!