【问题标题】:Have tasks permanently run in background in Console application让任务在控制台应用程序的后台永久运行
【发布时间】:2020-02-26 12:42:01
【问题描述】:

我将首先描述我想要实现的目标。这个想法是我有一个类的多个对象,它们有自己不同的计时器。当一个对象的计时器用完时,我希望该对象向控制台打印一条消息,然后重置计时器。我希望它在后台运行,以便我的应用程序可以在这些多个计时器在后台运行时继续工作。

例如像这样初始化(其中参数是以秒为单位的计时器):

BackGroundTimer timer1 = new BackGroundTimer(1);
BackGroundTimer timer2 = new BackGroundTimer(2);
BackGroundTimer timer3 = new BackGroundTimer(3);

Console.ReadLine();

Console.ReadLine() 代表正在进行的工作。然后我希望有以下输出:

0:

1:定时器1

2:定时器1定时器2

3:定时器1定时器3

4:定时器1定时器2

这有可能实现吗?

【问题讨论】:

  • 我在这里没有发现任何问题
  • 示例输出中的 0:、1:、2:、3: 和 4: 符号是什么?它们是从应用程序开始经过的秒数吗?

标签: c# async-await console-application


【解决方案1】:

看看Timer 类。您可以在其构造函数中指定周期,它会定期调用指定的方法。

编辑:下面的代码示例

static void Main(string[] args)
{
    Timer timer1 = new Timer(1000)
    {
        Enabled = true,
        AutoReset = true
    };

    Timer timer2 = new Timer(2000)
    {
        Enabled = true,
        AutoReset = true
    };

    Timer timer3 = new Timer(3000)
    {
        Enabled = true,
        AutoReset = true
    };

    timer1.Elapsed += async (sender, e) => await HandleTimer("Timer1");
    timer2.Elapsed += async (sender, e) => await HandleTimer("Timer2");
    timer3.Elapsed += async (sender, e) => await HandleTimer("Timer3");

    Console.ReadLine();
}

private static async Task HandleTimer(string message)
{
    Console.WriteLine(message);
}

【讨论】:

  • 谢谢你,我可以完成这项工作。我找到了一个类似的解决方案,使用带有 Task.Delay 的异步方法,但我决定切换到 Timer 版本,因为它看起来更干净。
猜你喜欢
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
相关资源
最近更新 更多