我正在尝试使用 Timer
触发事件以通过网络发送数据。我创建了一个简单的类来调试。基本上我有一个 List<string>
我想寄。我希望发生以下情况:
- 将字符串添加到
List
- 开始
Timer
10 秒 - 将第二个字符串添加到
List
之前Timer.Elapsed
- 重启
Timer
10 秒后返回。
到目前为止我有这个:
public static List<string> list;
public static Timer timer;
public static bool isWiredUp = false;
public static void Log(string value) {
if (list == null) list = new List<string>();
list.Add(value);
//this does not reset the timer, elapsed still happens 10s after #1
if (timer != null) {
timer = null;
}
timer = new Timer(10000);
timer.Start();
timer.Enabled = true;
timer.AutoReset = false;
if (!isWiredUp) {
timer.Elapsed += new ElapsedEventHandler(SendToServer);
isWiredUp = true;
}
}
static void SendToServer(object sender, ElapsedEventArgs e) {
timer.Enabled = false;
timer.Stop();
}
有什么想法吗?
最佳答案
您可以使用 Stop
函数后紧跟 Start
“重启”定时器的功能。使用它你可以创建 Timer
第一次创建类时,连接 Elapsed 事件,然后在添加项目时只调用这两个方法。它将启动或重新启动计时器。请注意,调用 Stop
在尚未启动的计时器上什么也不做,它不会抛出异常或导致任何其他问题。
public class Foo
{
public static List<string> list;
public static Timer timer;
static Foo()
{
list = new List<string>();
timer = new Timer(10000);
timer.Enabled = true;
timer.AutoReset = false;
timer.Elapsed += SendToServer;
}
public static void Log(string value)
{
list.Add(value);
timer.Stop();
timer.Start();
}
static void SendToServer(object sender, ElapsedEventArgs e)
{
//TODO send data to server
//AutoReset is false, so neither of these are needed
//timer.Enabled = false;
//timer.Stop();
}
}
请注意,而不是使用 List
您很可能想使用 BlockingCollection<string>
反而。这有几个优点。首先,Log
如果从多个线程同时调用,方法将起作用;多个并发日志可能会破坏列表。这也意味着 SendToServer
可以在添加新项目的同时将项目从队列中取出。如果您使用 List
你需要 lock
所有对列表的访问(这可能不是问题,但不是那么简单)。
关于c# - 重置 System.Timers.Timer 以防止 Elapsed 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14861047/