如何在C#中运行主函数一段时间后调用函数

本文关键字:函数 一段时间 调用 运行 | 更新日期: 2024-09-23 05:31:38

我在main函数中有一些代码,我想在随机时间(例如100毫秒)后通过调用另一个函数(如foo)来中断main函数。我该怎么做?例如,请参见以下内容:

void main()
{
    intsruction 1;
    intsruction 2;
    intsruction 3;// for example if 100 ms ends after executing instruction 
                  //3 the foo function should call after it, and after executing
                  //foo function, returns here and execute instruction 4
    intsruction 4;
    intsruction 5;
    intsruction 6;
}

foo函数:

void foo()
{
    instruction 7;
}

完成执行后,程序的流程可以是:

 intsruction 1;
 intsruction 2;
 intsruction 3;
 intsruction 7;// foo
 intsruction 4;
 intsruction 5;
 intsruction 6;

如何在C#中运行主函数一段时间后调用函数

您不能在某个时刻"中断"main,并在100ms后运行代码。相反,可以做的是在100ms后运行您感兴趣的代码(例如使用System.Timers.Timer)。之后,如果挂起主线程的原因是在某个时刻它们之间的依赖性,则在中,该点检查两个结果:maintimers,并做出适当的选择。这被称为推测执行,其中您运行假设的if分支的两种情况,并在之后选择适当的结果。注意:这种技术通常用于并行计算。

或者更好的是,您可以使用反应式扩展,不再担心中断。使用Rx,您可以根据您的需求设置完全解耦的定时数据推送,将被通知的客户端(您的程序)只需设置对Observable的订阅。你的代码看起来像这样:

 TheDataDesired.Subscribe(p=>{
      //the variable p now has the data.
 });

它类似于事件处理,但在某些方面更好,因为数据已经整理到订阅服务器的线程上。再加上对LINQ的广泛支持,您就可以通过等待数据到达来获得一种非常好的解耦方式。现在,它不一定只是数据,它可以是任何东西,包括系统上事件的处理。

我们的好朋友Lee Campbell很有礼貌地提供了一个很好的入门教程:http://www.introtorx.com/content/v1.0.10621.0/01_WhyRx.html

还有什么比订阅你想要的东西并开展你的业务更容易的呢?