很明显:例如,想象一下我表单中的一个按钮.当用户单击按钮时,应在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(); });更多推荐
在特定时间间隔后如何运行方法?
发布评论