使用timer调用多个函数 [英] Using timer to call multiple function

查看:103
本文介绍了使用timer调用多个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Windows窗体中使用计时器。我应该这样,我有4个函数被调用,5秒差异。在执行函数1()后执行它应该执行函数2()等。我正在使用C#我怎么能这样做?有任何帮助表示感谢。



我尝试过的事情:



我试过定时器中的单个函数调用。

解决方案

创建一个类级整数变量调用callNext。

然后在您的计时器勾选事件中:

<前一个=c#> 开关(callNext ++)
{
< span class =code-keyword> case 0 :Method0(); break ;
case 1 :Method1(); break ;
case 2 :Method2(); break ;
case 3 :Method3(); break ;
}
如果(callNext > 3 )callNext = 0 ;

为了更清楚,你可以使用 enum 而不是整数。


如果您需要确保每个方法完成后有五秒钟的延迟,而不是仅按顺序运行方法,如果每隔5秒调用一次方法,则可以使用基于任务的异步模式。在此示例中,响应按钮单击调用函数。这些函数将在UI线程上运行,但5秒延迟将是异步延迟,不会阻止UI线程。

  private   async   void  BtnRun_Click(对象发​​件人,EventArgs e)
{
function1();
await Task.Delay( 5000 );
function2();
await Task.Delay( 5000 );
function3();
await Task.Delay( 5000 );
function4();
}

如果函数都是操作,你可以使用一个重构方法列表<作用>


Hi, I want to use timer in windows forms.I should be such that I have 4 functions to be called with 5 sec difference.5secs after function1() execution it should execute function2() etc.I am working with C#.How can I do this?Any help appreciated.

What I have tried:

I have tried for single function call in timer.

解决方案

Create a class level integer variable call callNext.
Then in your Timer Tick event:

switch(callNext++)
   {
   case 0: Method0(); break;
   case 1: Method1(); break;
   case 2: Method2(); break;
   case 3: Method3(); break;
   }
if (callNext > 3) callNext = 0;

TO make it clearer, you could use an enum instead of an integer.


If you need to make sure that there is a five second delay after each method finishes rather than just running the methods sequentially, with a method being called every 5 seconds, you can use the task based asynchronous pattern. In this example the functions are called in response to a button click. The functions will run on the UI thread but the 5 second delay will be an asynchronous delay and will not block the UI thread.

private async void BtnRun_Click(object sender, EventArgs e)
        {
             function1();
            await Task.Delay(5000);
            function2();
            await Task.Delay(5000);
            function3();
            await Task.Delay(5000);
            function4();
        }

If the functions are all Actions you can refactor the method by using a List<Action>


这篇关于使用timer调用多个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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