C# 控制台应用程序最佳做法,用于一遍又一遍地 ping Web API,直到返回特定值



我有一个 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而不是秒表(或除了秒表之外(吗?

下面是使用计时器的示例。

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();