我想要一种方法,每15秒检查一次是否连接了特定设备/使用了该设备的驱动程序。
所以类似于:
Every 15 seconds
{
if (Device is connected)
{
do sth.;
exit loop;
}
}
到目前为止,我能够创建一个似乎可以工作的计时器:
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 15000;
timer.Elapsed += CheckConnection;
timer.Start();
}
不幸的是,一旦我的CheckConnection方法为true/发现设备已连接,我就不知道如何退出/中止计时器。
下面是一个示例应用程序,它展示了如何使用Polly的重试策略来实现所需的行为。
假设您的Device
类如下所示:
public class Device
{
private int ConnectionAttempts = 0;
private const int WhenShouldConnectionSucceed = 7;
public bool CheckConnection() => ConnectionAttempts == WhenShouldConnectionSucceed;
public void Connect() => ConnectionAttempts++;
}
- 每次调用
Connect
方法时,它都会增加ConnectionAttempts
- 当尝试计数器等于预定义值时,
CheckConnection
将返回true
(这模拟成功连接(,否则返回false
重试策略设置如下所示:
var retry = Policy<Device>.HandleResult(result => !result.CheckConnection())
.WaitAndRetryForever(_ => TimeSpan.FromSeconds(15),
onRetry: (result, duration) => Console.WriteLine("Retry has been initiated"));
var device = new Device();
retry.Execute(() =>
{
device.Connect();
return device;
});
- 直到给定的设备未连接(
!result.CheckConnection())
(,它将永远重试(WaitAndRetryForever
(Connect
方法 - 在每次重试尝试之间,它等待15秒(
TimeSpan.FromSeconds(15)
( onRetry
代表仅用于演示目的。onRetry
是可选的
所以,如果我有以下简单的控制台应用程序:
class Program
{
static void Main(string[] args)
{
var retry = Policy<Device>.HandleResult(result => !result.CheckConnection())
.WaitAndRetryForever(_ => TimeSpan.FromSeconds(15),
onRetry: (result, duration) => Console.WriteLine("Retry has been initiated"));
var device = new Device();
retry.Execute(() =>
{
device.Connect();
return device;
});
Console.WriteLine("Device has been connected");
}
}
然后它将在输出中打印以下行:
Retry has been initiated
Retry has been initiated
Retry has been initiated
Retry has been initiated
Retry has been initiated
Retry has been initiated
Device has been connected