C#控制台应用程序最佳实践,一次又一次地ping Web API,直到返回特定值

问题描述 投票:0回答:1

我有一个C#控制台应用程序,通常作为Windows服务安装,但也可以在控制台模式下运行(对于问题不是必需的,但只是给出上下文)。程序启动时,它会向Web API发送请求,以获取有关如何配置程序的数据。如果它所寻找的数据不存在,我希望它能够定期ping API,以防API最终获得其配置数据。

我想知道这样做的最佳做法是什么。这是我心目中的简化版本:

Stopwatch sw = Stopwatch.StartNew();
var response = null;
while (true)
{
    // Every 60 seconds, ping API to see if it has the configuration data.
    if (sw.Elapsed % TimeSpan.FromSeconds(60) == 0)
    {
        response = await PingApi();
        if (this.ContainsConfigurationData(response))
        {
            break;
        }
    }
}
this.ConfigureProgram(response);

没有这个配置数据,程序中没有其他任何东西发生,所以看起来像这样使用while循环和秒表应该没问题?不过,我不确定这是不是最好的做法。我也不确定是否应该对尝试次数设置限制,如果达到该限制会发生什么。而不是秒表(或秒表除外),我应该使用Thread.Sleep吗?

c# console-application
1个回答
1
投票

以下是使用Timer的示例。

var timer = new System.Timers.Timer();

timer.Interval = TimeSpan.FromSeconds(60).TotalMilliseconds;
timer.Elapsed += async (sender, e) => 
{
    timer.Stop();

    var response = await PingApi();

    if (ContainsConfigurationData(response))
    {
        ConfigureProgram(response);
    }
    else
    {
        timer.Enabled = true;
    }
};
timer.Enabled = true;

Console.WriteLine("Press any key to continue...");
Console.ReadKey();
© www.soinside.com 2019 - 2024. All rights reserved.