在特定时间间隔后如何运行方法? [英] How to run a method after a specific time interval?

查看:73
本文介绍了在特定时间间隔后如何运行方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显:例如,想象一下我表单中的一个按钮.当用户单击按钮时,应在30秒后运行一些void方法.

It's clear: For example, imagine a button in my form. When a user clicks on the button, some void method should run after 30 seconds.

会有一个空方法DoAfterDelay,它带有两个输入参数.第一个是执行方法(使用委托),第二个是时间间隔.所以我会得到:

There would be a void method DoAfterDelay that takes two input parameter. The first one is the method to do (using delegates), and the other one is the time interval. So I'll have:

public delegate void IVoidDelegate();
static void DoAfterDelay(IVoidDelegate TheMethod, TimeSpan Interval)
    {
        // *** Some code that will pause the process for "Interval".
        TheMethod();
    }

因此,我只需要一段代码就可以在特定时间间隔内暂停该过程.到目前为止,我使用以下代码来做到这一点:

So, I just need a piece of code to pause the process for a specific time interval. Heretofore, I used this code to do that:

System.Threading.Thread.Sleep(Interval);

但是此代码对我不利,因为它停止了整个过程并冻结了程序.我不希望程序陷入DoAfterDelay方法中.这就是Thread.Sleep没用的原因.

But this code is no good for me, because it stops the whole process and freezes the program. I don't want the program to get stuck in the DoAfterDelay method. That's why the Thread.Sleep is useless.

那么有人可以提出更好的方法吗?当然,我已经进行了搜索,但是我发现的大多数解决方案都是基于使用计时器的(例如

So could anyone suggest a better way? Of course I've searched about that, but most of the solutions I've found were based on using a timer (like here for example). But using a timer is my last opinion, because the method should run once and using timers makes the program confusing to read. So I'm looking for a better solution if there is. Or maybe I have to use timers?

我想我必须使用线程,但是不确定.所以我想知道是否有人可以引导我找到解决方案.预先感谢.

I guess I have to play with threads, but not sure. So I wonder if anyone could guide me to a solution. Thanks in advance.

推荐答案

您可以使用任务吗?

    Task.Factory.StartNew(() =>
    {
        System.Threading.Thread.Sleep(Interval);
        TheMethod();
    });

这篇关于在特定时间间隔后如何运行方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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