给定延迟后执行方法的简便方法? [英] Easy way to excecute method after a given delay?

查看:73
本文介绍了给定延迟后执行方法的简便方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有简单的方法可以在给定的延迟后像在iOS中那样立即执行方法?

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

在iPhone上,我会这样做:

On iPhone I would do this:

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

然后,它将安排2.5秒后在主线程(UI线程)上执行方法connectSensor.并且由于它是在主线程上自动调度的,因此您不必担心跨线程问题. (还有一个performSelectorOnBackground版本)

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)

那我该如何在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);            
    } 

如何将其封装到扩展方法中,以便我可以调用this.Perform(MyMethod, null, 2500);?

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

推荐答案

您可以像这样使用BackgroundWorker:

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

后台工作者将在UI线程之外的线程上运行睡眠,因此您的应用程序可以在发生延迟时自由地执行其他操作.

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.

这篇关于给定延迟后执行方法的简便方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆